我想編寫一個例程,它從Excel VBA表單中獲取可用工作表的用戶選擇並將它們導出到一個PDF文檔中。我計劃使用此功能導出到Word和PowerPoint例程。我已經嘗試了Stack Overflow的幾個被認爲有效的想法。我沒有運氣。我也嘗試了其他來源的各種想法......也許我對明顯的盲目了。我試過使用一個數組(arrSheets,仍然在代碼中,我希望也許我仍然可以使用它)。它使用表單對象填充,但使用動態數組和redim命令對我沒有效果。激活多個工作表使用VBA導出
我在這裏得到的代碼似乎很好地工作,直到涉及到「ActiveSheet.ExportAsFixedFormat ...」行。在這一點上,我得到「應用程序定義或對象定義的錯誤(運行時錯誤1004)」
從VBA窗體上的命令按鈕下面的代碼火災...
Private Sub cmdExport_Click()
'Find the selected documents from the form's checkboxes and send to the export routine
Dim intArrayCounter, intSelectionNum As Integer
Dim bolFound As Boolean
Dim ctrl As control
Dim arrSheets(1 To 6) As Variant ' the array to hold the worksheet objects...
intSelectionNum = 0 ' which checkbox is it
intArrayCounter = 1 ' array index
bolFound = False ' was a checked box found?
For Each ctrl In frmToPDF.Controls
If TypeName(ctrl) = "CheckBox" Then
intSelectionNum = intSelectionNum + 1 ' set the selection number
If ctrl.Value = True Then
bolFound = True ' found a selection set the flag to true
Set arrSheets(intArrayCounter) = Sheets(intSelectionNum)
ThisWorkbook.Sheets(intSelectionNum).Select
' increment the counter
intArrayCounter = intArrayCounter + 1
End If
End If
Next
'Sheets(arrSheets).Select <---remmed out cause this throws an error
If bolFound = False Then ' if there is Nothing selected send a message, or do the deal...
Call MsgBox("There is nothing selected to export!", vbOKOnly, "Nothing selected...")
Else
frmExport.Caption = "Processing the document...Please be patient!"
ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:="C:\test.pdf", Quality:=xlQualityStandard, IgnorePrintAreas:=False, DisplayFileAfterPublish:=True
'the above Activesheet routine throws "Application-defined or Object-defined error (Run-time error 1004)"
End If
ThisWorkbook.Sheets(intSheet).Select
End Sub
灰溶液應該工作。至於'ReDim'語句,您是否使用過'ReDim Preserve'來保留數組中現有的數據,然後將其調整到新的維度。 – EEM
忘記包含此之前:[ReDim聲明](https://msdn.microsoft.com/en-us/library/office/gg251578(v=office.15).aspx) – EEM