我想根据userform复选框状态选择多个工作表,我在选择时收到错误。我的用户表单中总共有16个复选框,因此我需要一种方法来确定要选择的工作表。
简短示例:
`Sub chkboxes()'
DIM SheetNames as string
If CB1.value = true then
SheetNames = "SummaryReport"
End IF
If CB2.value = true and sheetNames <> "" then
SheetNames = Sheetnames & "," & "WeekdaysReport"
elseif CB2.value = true and sheetnames = "" then
SheetNames = "WeekdaysReport"
End If
If CB3.value = true and sheetnames <> "" then
SheetNames = SheetNames & "," & "WeekendsReport"
elseif CB3.value = true and SheetNames <> "" then
SheetNames = "WeekendsReport"
End If
If SheetNames = ""
Exit Sub
End If
Sheets(Array(SheetNames)).select **'This is where the script stops and prompt error.**
Call ExportToPDF
SheetNames = ""
End Sub
以上是非常业余的,我对vba和编程仍然非常不熟悉。希望我能得到一些指导。感谢。
我尝试在线搜索解决方案,但未能找到类似的帖子。
答案 0 :(得分:1)
我认为这是一种更简单的方法。而不是复选框,使用也可以多选的列表框。在用户表单后面的代码中执行以下操作:
Private Sub UserForm_Initialize()
With ListBox1
.AddItem "SummaryReport"
.AddItem "WeekdaysReport"
.AddItem "WeekendReport"
End With
End Sub
Private Sub CommandButton1_Click()
With ListBox1
Dim i As Integer
Do Until i = .ListCount
If .Selected(i) Then
Sheets(.ListIndex + 1).Select
'MsgBox Sheets(i + 1).Name
'do something with selected sheet
End If
i = i + 1
Loop
End With
End Sub
答案 1 :(得分:0)
您的代码中有不必要的“数组”功能调用以及其他一些“快捷方式”。
请更换以下内容:
Sheets(Array(SheetNames)).select
Call ExportToPDF
使用此代码段:
Dim aSheetNames() As String
Dim i as long
aSheetNames = Split(SheetNames,",")
For i = LBound(aSheetNames) To UBound(aSheetNames)
Sheets(aSheetNames(i)).select
ExportToPDF
Next
而且,我希望,如果我的假设是对的,现在程序应该有效。
Ups,我发现了另一个问题...... 如果我正确猜测你的内涵,每个CheckBox的resposible代码应如下所示:
If CB2.Value Then
If SheetNames <> "" Then SheetNames = Sheetnames & ","
SheetNames = Sheetnames & "WeekdaysReport"
End If