gpt4 book ai didi

vba - Excel 2010 中的动态打印范围

转载 作者:行者123 更新时间:2023-12-04 15:27:17 24 4
gpt4 key购买 nike

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

=OFFSET('Slide Sheet Print Lateral'!$A$27, 0, 0, COUNTA('Slide Sheet Print Lateral'!$A:$A), COUNTA('Slide Sheet Print Lateral'!$1:$1))

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

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

我收到错误“运行时错误‘1004’”

有人能帮忙吗?

最佳答案

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

  • 您在幻灯片打印横向工作表上(否则对 Activesheet 的引用将会中断,因为您试图将事件工作表的打印范围设置为不同工作表上的范围);和
  • Slide Sheet Print Lateral 表的 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

关于vba - Excel 2010 中的动态打印范围,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13554708/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com