将excel中的打印区域设置为相对引用

时间:2015-05-27 13:30:25

标签: excel-vba printing relative vba excel

我想创建一个循环,在工作簿上打印选定的范围。我选择了一个相对范围,存储为" Arge"。

问题:我想将打印区域设置为所选范围。

Range("A1").Select
ActiveCell.Offset(1, 0).Range("A1:P37").Select
Dim Arge As Range
Set Arge = Selection             'PROBLEM
 'do loop and other code

With ActiveSheet.PageSetup
    .PrintTitleRows = ""
    .PrintTitleColumns = ""
End With
ActiveSheet.PageSetup.PrintArea = Arge            'PROBLEM with Arge

1 个答案:

答案 0 :(得分:0)

两件事

  1. 避免使用.Select。您可能希望查看This
  2. .PrintArea采用字符串(范围地址)而不是范围本身。您可能希望查看This
  3. <强>代码

    Sub Sample()
        Dim ws As Worksheet
        Dim Arge As Range
    
        Set ws = ThisWorkbook.Sheets("Sheet1")
        Set Arge = ws.Range("A1:P37")
    
        With ws.PageSetup
            .PrintTitleRows = ""
            .PrintTitleColumns = ""
            .PrintArea = Arge.Address
        End With
    End Sub
    

    注意

    如果您确实需要使用Selection对象,请确保它是有效范围。例如

    '~~> Check if what the user selected is a valid range
    If TypeName(Selection) <> "Range" Then
        MsgBox "Select a range first."
        Exit Sub
    Else
        Set Arge = Selection
    End If