我有这段代码,不会填充工作表名称以便在PDF中打印。我得到一个超出范围编译错误的下标。有什么想法吗?
Application.ScreenUpdating = False
Sheets("Macros").Select
Dim strPath As String, strFileName As String
Dim i As Integer, y As Integer, x As Integer
Dim WkstNames() As Variant
Dim iCount As Integer, iWkstCount As Integer
Dim printrange As Range
Set printrange = Range("P222:P248")
Dim p() As Variant
iCount = 1
iWkstCount = ThisWorkbook.Sheets.Count
ReDim WkstNames(1 To iWkstCount)
ReDim p(1 To 27)
For y = 1 To iWkstCount
For x = 1 To 27
printrange.Rows(p(x)).Select
If ActiveCell = "True" Then WkstNames(y) = Sheets(iCount).Name
iCount = iCount + 1
Next x
Next y
Sheets(WkstNames).Select ' error occurs here
答案 0 :(得分:0)
原因其实很简单。您正在开始重新调整数组,并且您的行WkstNames(y) = Sheets(iCount).Name
未执行,因此您在数组中至少获得一个空值。
在创建数组后尝试并遍历数组。使用此代码
For i = LBound(WkstNames) To UBound(WkstNames)
Debug.Print WkstNames(i)
Next i
Worksheets(WkstNames).Select
您会注意到至少有一个值为空,因此Excel无法找到该表。
一个工作示例就像是
Dim WkstNames(1 To 2) As String
WkstNames(1) = "Sheet1"
WkstNames(2) = "Sheet2"
Worksheets(WkstNames).Select
示例(评论后续跟踪)
这只是一个示例,说明如何在不事先声明数组的情况下选择工作表。
Sub Sample()
Dim Ar
Dim wsName As String, sDelim As String
sDelim = "|"
With ThisWorkbook
For i = 1 To .Sheets.Count
If .Sheets(i).Name Like "Sheet*" Then
If wsName = "" Then
wsName = .Sheets(i).Name
Else
wsName = wsName & sDelim & .Sheets(i).Name
End If
End If
Next i
If InStr(1, wsName, sDelim) Then
Ar = Split(wsName, sDelim)
Else
Ar = wsName
End If
.Sheets(Ar).Select
End With
End Sub