简体   繁体   中英

Assign a range to a range variable using ActiveCell.Offset functions in VBA

I'm trying to offset from the current active cell in Excel to define a range and assign it to a variable, so that I can then change some of its properties. This does not work:

Public Sub tester()
    Dim myRange As Range
    myRange = Range(ActiveCell.Offset(1, 0), ActiveCell.Offset(1, 7))
    myRange.Font.Color = RGB(200, 100, 0)
End Sub

在此处输入图像描述

In the debugger:

在此处输入图像描述

Although this does work:

Public Sub tester()
    Range(ActiveCell.Offset(1, 0), ActiveCell.Offset(1, 7)).Font.Color = RGB(200, 100, 0)
End Sub

在此处输入图像描述

What's going on here? Isn't myRange a range? It doesn't seem to want to assign. How do I perform this kind of operation that is, putting a range into a variable and then using that variable to reference it?

The assignment does not contain the "Set" operator I am reliably informed. This will work:

Public Sub tester()
    Dim myRange As Range
    Set myRange = Range(ActiveCell.Offset(1, 0), ActiveCell.Offset(1, 7))
    myRange.Font.Color = RGB(200, 100, 0)
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM