将一些excel工作表保存为PDF

Option Explicit Dim mySheets As Dictionary Private Sub SaveAndOpen_Click() 'set up variables Dim i As Long Dim j As Long Dim myArr() As Long Dim filename As String ReDim myArr(1 To Sheets.Count) j = 1 'make bounds Dim from As Long Dim tonum As Long 'numbers inputted from a userform from = FromBox.Value tonum = ToBox.Value filename = Cells(3, 4) & "." & mySheets.Item(from) & "-" & mySheets.Item(tonum) For i = 1 To mySheets.Count If i >= FromBox.Value And i <= ToBox.Value Then myArr(j) = i j = j + 1 End If Next i Dim filepath As String For i = 1 To UBound(myArr) filepath = filepath & myArr(i) Next i filepath = "c:\file\path\here\" ThisWorkbook.Sheets(myArr).Select ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, filename:= _ filepath & filename, Quality:=xlQualityStandard, IncludeDocProperties:=True, _ IgnorePrintAreas:=False, OpenAfterPublish:=True ThisWorkbook.Sheets(1).Select End Sub Private Sub UserForm_Initialize() Copies.Value = 1 FromBox.Value = 1 Dim i As Long Set mySheets = New Dictionary For i = 1 To ActiveWorkbook.Sheets.Count mySheets.Add i, ActiveWorkbook.Sheets(i).Name SheetBox.Value = SheetBox.Value & i & " - " & ActiveWorkbook.Sheets(i).Name & vbCrLf Next i ToBox.Value = i - 1 End Sub 

这个子程序从一个用户表单获取信息,用户表单在FromBox和ToBox中有用户input的variables; 这些都是漫长的。 目标是能够保存,例如,工作表2-10。参数由用户指定。

当用户指定所有的工作表(IE有10个工作表,而用户指定范围1-10)时,下面的代码将被取消注释。 但是当用户指定2-10时,失败。

我想这个问题是我想要用9个元素长的数组select10个元素。

正如斯科特·霍尔兹曼(Scott Holtzman)在评论中指出的那样,你正在将myArr大小设定得比它应该大一些。 因此,它有未分配的值,它们被保留为默认零值,并且由于没有要select的工作表0而导致问题。

我认为下面的代码应该工作:

 Option Explicit Dim mySheets As Dictionary Private Sub SaveAndOpen_Click() 'set up variables Dim i As Long Dim j As Long Dim myArr() As Long Dim filename As String 'make bounds Dim from As Long Dim tonum As Long 'numbers inputted from a userform from = FromBox.Value tonum = ToBox.Value 'Check ToBox.Value is valid If tonum > Sheets.Count Then MsgBox "Invalid To value" Exit Sub End If 'Check FromBox.Value is valid If from > tonum Then MsgBox "Invalid From value" Exit Sub End If 'Setup myArr ReDim myArr(from To tonum) For j = from To tonum myArr(j) = j Next filename = Cells(3, 4) & "." & mySheets.Item(from) & "-" & mySheets.Item(tonum) ' Dim filepath As String 'For i = LBound(myArr) To UBound(myArr) ' filepath = filepath & myArr(i) 'Next i filepath = "c:\file\path\here\" ThisWorkbook.Sheets(myArr).Select ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, filename:= _ filepath & filename, Quality:=xlQualityStandard, IncludeDocProperties:=True, _ IgnorePrintAreas:=False, OpenAfterPublish:=True ThisWorkbook.Sheets(1).Select End Sub