Excel 通过检查工作簿中的sheetname关闭userform

Excel 通过检查工作簿中的sheetname关闭userform,excel,vba,Excel,Vba,通过使用commandbotton,可以通过检查工作簿中是否存在特定的工作表名称来关闭userform Private Sub Close1_Click() ' Protect and Hide Dim ws As Worksheet For Each ws In ThisWorkbook.Sheets If InStr(1, ws.Name, "FSS-TEM-00025") Then (ws.Name, "FSS-TEM-00025" )

通过使用commandbotton,可以通过检查工作簿中是否存在特定的工作表名称来关闭userform

Private Sub Close1_Click()
' Protect and Hide

 Dim ws As Worksheet

    For Each ws In ThisWorkbook.Sheets
        If InStr(1, ws.Name, "FSS-TEM-00025") Then
            (ws.Name, "FSS-TEM-00025" ).Select
            ActiveSheet.Protect DrawingObjects:=True, Contents:=True, Scenarios:=True
            ActiveWindow.SelectedSheets.Visible = False
            Unload Me
        Else
            Unload Me
        End If
    Next

    'Unload Me
End Sub

这会奏效的。在If之后,您没有正确使用ws引用

Private Sub Close1_Click()
' Protect and Hide

Dim ws As Worksheet

For Each ws In ThisWorkbook.Sheets
    If InStr(1, ws.Name, "FSS-TEM-00025") Then
        ws.Select 'this line is different
        ActiveSheet.Protect DrawingObjects:=True, Contents:=True, Scenarios:=True
        ActiveWindow.SelectedSheets.Visible = False 'hides the activesheet
        Unload Me
    End If
Next

'Unload Me
End Sub
而不是选择然后使用activesheet:

ws.Select 'this line is different            
ActiveSheet.Protect DrawingObjects:=True, Contents:=True, Scenarios:=True
可能只是

ws.Protect DrawingObjects:=True, Contents:=True, Scenarios:=True

谢谢雅各布!!!它现在确实有效,但我需要避免一件事。当我运行这个表单时,表单的按钮会隐藏在其中。你能告诉我如何解决这个问题吗?如果你不想隐藏工作表,请注释掉设置
.Visible=False
的行。我还取出了
Else
语句,因为表单正在被卸载,即使它没有找到表单。