首页 > 解决方案 > 从用户输入设置打印区域的宏

问题描述

这是我现在正在使用的代码。

Sub PrintArea()
Dim arange
    Rows = InputBox("How many Rows do you want to print (Between 1 and 48)?", "Row Selection")
.PageSetup.PrintArea = .Range(A, B, C).Rows
End Sub

当我尝试运行宏时,我得到“编译错误:无效或不合格的引用”,它突出显示了我的代码中的 .Range。

我希望打印区域始终为 AC 列,但行将在 2-48 之间变化,具体取决于我要打印的内容。

编辑:单步执行代码,它停在这一行,

ActiveSheet.PageSetup.PrintArea = .Range(A:C, "arange") 

并给我一个语法错误。

标签: excelvba

解决方案


它应该是这样的:

Option Explicit

Sub SetMyPrintArea()
    Dim UserInput As Variant

    Do
        UserInput = Application.InputBox(Prompt:="How many Rows do you want to print (Between 1 and 48)?", Title:="Row Selection", Type:=1)
        If VarType(UserInput) = vbBoolean And UserInput = False Then Exit Sub
        DoEvents
    Loop While UserInput < 2 Or UserInput > 48

    Worksheets("Sheet1").PageSetup.PrintArea = "A1:C" & UserInput
End Sub
  • 请注意,Do … Loop While UserInput < 2 Or UserInput > 48强制输入框再次出现,直到用户输入介于 2 … 48 之间的值。

  • If VarType(UserInput) = vbBoolean And UserInput = False Then Exit Sub是为了检查用户是否按下了取消按钮然后中止。

  • 不要命名您的过程PrintArea,因为 Excel 已经使用了它PageSetup.PrintArea并且很容易混淆。


推荐阅读