【问题标题】:Dynamic Print Range in Excel 2010Excel 2010 中的动态打印范围
【发布时间】:2012-11-13 07:56:59
【问题描述】:

我正在尝试设置动态打印范围以打印工作簿中的工作表,该工作簿是从同一工作簿中的另一个工作表填充的。 我似乎遇到了麻烦。我在名称管理器中设置了一个名为横向的命名范围,如下所示:

=OFFSET('横向打印幻灯片'!$A$27, 0, 0, COUNTA('横向打印幻灯片'!$A:$A), COUNTA('横向打印幻灯片'!$1:$1) )

我一直在尝试编写 VBA 代码(我对 VBA 一无所知)我有这个...

Sub Printarea()
    ActiveSheet.PageSetup.Printarea = "lateral"
End Sub

我收到一个错误“运行时错误'1004'”

谁能帮忙?

【问题讨论】:

  • 显然我没有使用您的电子表格,但我根据您的代码在本地进行了测试,它似乎可以正常工作,没有任何错误。
  • 确保lateral 是在工作簿级别而不是工作表级别定义的,否则您可能必须使用Slide Sheet Print Lateral!lateral 限定名称。更多详情见this MSDN

标签: vba excel-2010


【解决方案1】:

最后两个参数指定“横向”范围的高度和宽度。他们计算非空单元格的数量。像 Neil 一样,我发现您的代码没有问题,前提是:

  • 您在幻灯片打印横向工作表上(否则对 Activesheet 的引用将失败,因为您试图将活动工作表的打印范围设置为不同工作表上的范围);和
  • 在幻灯片打印侧页的 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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-06-16
    • 2021-09-13
    • 1970-01-01
    相关资源
    最近更新 更多