我有以下問題,在我的 VBA 代碼中,當我想將范圍保存為 PDF 時,它涉及運行時錯誤 5 無效程序呼叫或引數。代碼如下所示:
Worksheets(2).Range("A1:G103").ExportAsFixedFormat Type:=xlTypePDF, Filename:=path1_1 & "\Idea" & Worksheets(3).Range("B12").Value & ".pdf", OpenAfterPublish:=False
正在訪問的作業表是隱藏的。如果Worksheets(2).Visible = True. 如何撰寫代碼以使錯誤訊息不再出現并且我不必顯示作業表?知道為什么會發生錯誤也很好。我真的很感謝你的幫助。
Worksheets(2).Visible = True
Worksheets(2).Range("A1:G103").ExportAsFixedFormat Type:=xlTypePDF, Filename:=path1_1 & "\Idea" & Worksheets(3).Range("B12").Value & ".pdf", OpenAfterPublish:=False
Worksheets(2).Visible = xlVeryHidden
這就是 VBA 代碼的作業方式,但不幸的是,這不是一個選項。
uj5u.com熱心網友回復:
沒有辦法ExportAsFixedFormat在隱藏的作業表上使用(但是微軟沒有說明事實或原因)。因此,如果要匯出作業表,則沒有其他方法可以使其暫時可見。但是,您可以通過設定來防止用戶在此期間看到作業表Application.ScreenUpdating = False。要確保在任何情況下都將作業表設定為不可見(并且再次啟用 ScreenUpdating),請使用錯誤處理程式。
Sub exportSheet()
Application.ScreenUpdating = False
With ThisWorkbook.Sheets(2)
On Error GoTo ExportError
.Visible = True
.Range("A1:G103").ExportAsFixedFormat Type:=xlTypePDF, Filename:="(your path here)", OpenAfterPublish:=False
ExportError:
.Visible = False
Application.ScreenUpdating = True
End With
End Sub
uj5u.com熱心網友回復:
匯出為 PDF:非常隱藏的作業表
Sub ExportToPDF()
Const path1_1 As String = "C:\Test"
' Reference the range.
Dim wb As Workbook: Set wb = ThisWorkbook
Dim ws As Worksheet: Set ws = wb.Worksheets(2)
Dim rg As Range: Set rg = ws.Range("A1:G103")
Dim FilePath As String: FilePath = path1_1 & Application.PathSeparator _
& "Idea" & CStr(wb.Worksheets(3).Range("B12").Value) & ".pdf"
' Store the row heights and column widths in arrays.
Dim rCount As Long: rCount = rg.Rows.Count
Dim cCount As Long: cCount = rg.Columns.Count
Dim rgHeights() As Double: ReDim rgHeights(1 To rCount)
Dim rgWidths() As Double: ReDim rgWidths(1 To cCount)
Dim n As Long
For n = 1 To rCount
rgHeights(n) = rg.Cells(n, 1).RowHeight
Next n
For n = 1 To cCount
rgWidths(n) = rg.Cells(1, n).ColumnWidth
Next n
' In a new instance of Excel, add a new workbook
' and reference its 1st worksheet and the range.
Dim xlApp As Excel.Application: Set xlApp = New Excel.Application
'xlApp.Visible = True ' use while developing; default is 'False'
Dim dwb As Workbook: Set dwb = xlApp.Workbooks.Add
Dim dws As Worksheet: Set dws = dwb.Sheets(1)
Dim drg As Range: Set drg = dws.Range("A1").Resize(rCount, cCount)
' Copy
rg.Copy
dws.Paste ' copies to cell 'A1'
Application.CutCopyMode = False
' Apply the stored row heights and column widths to the copied range.
For n = 1 To rCount
drg.Rows(n).RowHeight = rgHeights(n)
Next n
For n = 1 To cCount
drg.Columns(n).ColumnWidth = rgWidths(n)
Next n
' Export
drg.ExportAsFixedFormat _
Type:=xlTypePDF, _
Filename:=FilePath ' , _
OpenAfterPublish:=True ' use while developing; default is 'False'
' Close & quit.
dwb.Close SaveChanges:=False
xlApp.Quit
End Sub
轉載請註明出處,本文鏈接:https://www.uj5u.com/gongcheng/526506.html
標籤:擅长vba运行时错误
