最後兩個參數指定範圍「lateral」的高度和寬度。他們計算非空單元的數量。像尼爾,我發現你的代碼沒有問題的前提是:
- 您是在幻燈片頁打印橫向片(否則參考Activesheet將BARF因爲你想設置打印範圍活動工作表不同紙張上的範圍); AND
- 「幻燈片打印橫向」頁面的A列和第1行中有一些內容。但是,如果沒有,則會爲零範圍指定高度和/或寬度。這是一個無效的範圍參考,然後你會得到1004錯誤。
您可以安全避免的唯一方法是在分配範圍之前獲取VBA代碼中的CountA值;如果其中任一個爲零,則警告用戶並中止。
我還建議您不要使用方法或屬性名稱來處理這樣的過程;你經常可以擺脫它,但有時它可能會導致問題。調用像SetMyPrintRange這樣的程序是安全的。
編輯:經過反思,我不會爲檢查計數而煩擾;只是試圖獲得對範圍的參考,如果你不能,然後告訴用戶該做什麼。試試這個:
Sub SetMyPrintArea()
Dim l As Long
Dim wks As Excel.Worksheet
Dim rng As Excel.Range
'Check that the worksheet exists.
On Error Resume Next
Set wks = ThisWorkbook.Worksheets("Slide Sheet Print Lateral")
On Error GoTo ErrorHandler
'If it doesn't, throw an error which will send it to the error handler.
If wks Is Nothing Then
Err.Raise vbObjectError + 20000, , _
"The worksheet Slide Sheet Print Lateral is not in this workbook."
End If
'Try to get the reference to the range. If we can't, there's something wrong.
On Error Resume Next
Set rng = wks.Range("lateral")
On Error GoTo ErrorHandler
If rng Is Nothing Then
Err.Raise vbObjectError + 20000, , _
"Cannot find the range named 'lateral'. Please ensure that there is " _
& "content in row 1 and column A of the Slide Sheet Lateral sheet."
End If
wks.PageSetup.Printarea = "lateral"
ExitPoint:
'Just cleaning up the object references
'to leave the place tidy...
On Error Resume Next
Set rng = Nothing
Set wks = Nothing
On Error GoTo 0
Exit Sub
ErrorHandler:
'Display the message and go to the exit point.
MsgBox "Error " & Err.Number & vbCrLf & Err.Description
Resume ExitPoint
End Sub
顯然我沒有使用你的電子表格,但我根據你的代碼在本地做了一個測試,它似乎沒有任何錯誤地工作。 – Neil
確保'lateral'在工作簿級別而不是在工作表級別上定義,否則您可能必須使用'Slide Sheet Print Lateral!lateral'限定名稱。請參閱[此MSDN](https://office.microsoft.com/en-us/excel-help/define-and-use-names-in-formulas-HA010147120.aspx)以獲取更多詳細信息 – SeanC