我刚刚开始自学编码。我有一个工作簿,大约有14个选项卡/工作表供员工输入他们每天的工作时间。在"摘要"选项卡,并希望为每个员工创建一个宏按钮,以单击查看他/她的选项卡。这些员工标签是隐藏的,我希望操作可以取消隐藏,然后在员工点击按钮时隐藏。
不幸的是,我收到了一个不明确的错误消息,我为每个员工创建了一个模块。我想我需要某种方式" stack"代码,但再次对编码来说是全新的。以下是我的代码示例
Private Sub ShowHideWorksheets()
Sheets("EMPLOYEE 1").Visible = Not Sheets("EMPLOYEE 1").Visible
End Sub
答案 0 :(得分:1)
你需要正确地把它放在一个按钮后面。将按钮插入页面时,右键单击它并指定宏。代码看起来像
Sub Button1_Click()
Sheets("EMPLOYEE 1").Visible = Not Sheets("EMPLOYEE 1").Visible
End Sub
答案 1 :(得分:0)
如果您将Private更改为Public,它应该可以正常工作。我假设你现在只是在创建宏以使基本功能正常工作。你可以隐藏(作为你发布的代码)并取消隐藏:
' This first macro actually just makes the worksheet visible and then
' invisible each time you execute it - so I'm not sure if
' that's what you're after
Public Sub ShowHideWorksheets()
Sheets("EMPLOYEE 1").Visible = Not Sheets("EMPLOYEE 1").Visible
End Sub
' If it's invisible you can do this.
Public Sub ShowWorksheets()
Sheets("EMPLOYEE 1").Visible = True
End Sub
' Basically that should give you an idea of how to proceed.
答案 2 :(得分:0)
基本上您希望切换工作表的可见性。 假设您知道哪个Sheet将被触发,它是这样的:
Public Sub TriggerSheetVisibility(worksheetname as string)
Dim ws as WorkSheet
On Error Resume Next 'To avoid subscript out of range error if a worksheetname is passed that doesn't exit
Set ws = Worksheets(worksheetname)
On Error Goto 0
If Not ws Is Nothing Then 'Only when the worksheet exists, we can execute the rest of this sub:
If ws.Visible = True then
ws.Visible = False
Else
ws.Visible = True
End If
End If
End Sub
另见https://msdn.microsoft.com/en-us/library/office/ff197786.aspx
答案 3 :(得分:0)
这也是一种可以接受的方法吗?尽管很长时间啰嗦
Private Sub CommandButton1_Click()
Dim sheet As Worksheet
For Each sheet In ActiveWorkbook.Sheets
If sheet.Name <> CommandButton1.Caption Then
sheet.Visible = False
End If
If sheet.Name = CommandButton1.Caption Then
sheet.Visible = True
End If
Next sheet
End Sub
但是我更喜欢这个,因为你只需要一个按钮
Private Sub CommandButton1_Click()
Dim sheet As Worksheet
For Each sheet In ActiveWorkbook.Sheets
If sheet.Name <> Environ("USERNAME") Then
sheet.Visible = False
End If
If sheet.Name = Environ("USERNAME") Then
sheet.Visible = True
End If
Next sheet
End Sub