最后两个参数指定范围“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