我想使用Sheets(Array())方法选择一个工作表数组。 我想要选择的工作表在我的工作表Printlist的单元格中命名。 工作表名称列在D列到K列之间。
并非所有单元格都被填充,因此如果我使用下面的函数,它会在具有空白单元格的行上出错。如何避免此错误:
这是代码
Sub PDF_maken()
Dim ws As Worksheet
Dim LR As Long
Dim r As Range
Dim Mypath As String
Dim strarray As String
Set ws = ActiveWorkbook.Worksheets("Printlijst")
LR = ws.Cells(Rows.Count, 1).End(xlUp).Row
For Each r In ws.Range("B20:B20").Cells
If Not IsEmpty("B" & r.Row) Then
Mypath = ws.Range("B" & r.Row).Text
colCheck = 4
Do Until Cells(r.Row, colCheck) = ""
strarray = strarray & IIf(colCheck > 4, ",") & """" & Cells(r.Row, colCheck).Value & """"
colCheck = colCheck + 1
Loop
ActiveWorkbook.Sheets(strarray).Select
ActiveWorkbook.SelectedSheets.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=Mypath & ws.Range("C" & r.Row).Text & ".pdf", _
Quality:=xlQualityStandard, IncludeDocProperties:=True, _
IgnorePrintAreas:=False, OpenAfterPublish:=False
End If
Next r
End Sub
答案 0 :(得分:0)
做一个类似的循环,
类似
colCheck=4
do until cells(r.row,colCheck)=""
strArray=strarray & iif(colCheck>4,",","") & cells(r.row,colCheck).value
colCheck=colCheck+1
loop
然后你会得到类似a,b,c的东西我没有测试过这个,所以可能需要一些调整。我马上回过头来看看。
答案 1 :(得分:0)
您可以使用常规数组而不是Array()
函数来创建数组。然后,您可以遍历包含工作表名称的单元格,只有在它们不是空白时才添加它们。这是一个例子。
Sub PDF_maken()
Dim ws As Worksheet
Dim lLastRow As Long
Dim rMap As Range
Dim sPath As String
Dim aSheets() As String
Dim lShCnt As Long
Dim rSh As Range
Set ws = ActiveWorkbook.Worksheets("Printlist")
lLastRow = ws.Cells(ws.Rows.Count, 1).End(xlUp).Row
For Each rMap In ws.Range("B2:B" & lLastRow).Cells
'Make sure there's a path
If Not IsEmpty(rMap.Value) Then
sPath = ws.Range("B" & rMap.Row).Text
're-dimension an array to hold all the sheet names
ReDim aSheets(1 To Application.WorksheetFunction.CountA(rMap.Offset(, 2).Resize(1, 8)))
'reset the counter
lShCnt = 0
'loop through all the cells that might have a sheet name
'and add them to the array
For Each rSh In rMap.Offset(, 2).Resize(1, 8).Cells
If Not IsEmpty(rSh.Value) Then
lShCnt = lShCnt + 1
aSheets(lShCnt) = rSh.Text
End If
Next rSh
ActiveWorkbook.Sheets(aSheets).Select
ActiveSheet.ExportAsFixedFormat xlTypePDF, sPath & rMap.Offset(0, 1).Text & ".pdf"
End If
Next rMap
ws.Select
End Sub
如果你得到Error 9: Subscript Out of Range
,有三件事要检查:
Sheets()
。始终使用ThisWorkbook.Sheets()
或其他一些工作簿参考。这将确保您不会尝试访问您不打算使用的工作簿中的工作表。sheets(array(1234,4567)).select
与sheets(array("1234","4567")).select
不同。您必须将字符串传递给表格,否则您将收到该错误。的种类。您可以传递数字,但它会根据索引号而不是其名称选择工作表。这就是为什么当你的工作表名称看起来像数字时你必须格外小心。