我正在尝试设置动态打印范围,以在同一工作簿中的另一个工作表中填充的工作簿中打印工作表。 我好像遇到了麻烦。我在Name Manager中设置了一个名为lateral的命名区域,如下所示:
= OFFSET('幻灯片打印横向'!$ A $ 27,0,0,COUNTA('幻灯片打印横向'!$ A:$ A),COUNTA('幻灯片打印横向'!$ 1:$ 1) )
我被困在尝试编写VBA代码(我对VBA一无所知)我有这个......
Sub Printarea()
ActiveSheet.PageSetup.Printarea = "lateral"
End Sub
我收到错误“运行时错误'1004'”
有人可以帮忙吗?
答案 0 :(得分:0)
最后两个参数指定范围“横向”的高度和宽度。他们计算非空单元格的数量。像Neil一样,我发现您的代码没有问题,但是:
唯一可以安全避免的方法是在分配范围之前获取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