简体   繁体   中英

setting ranges using 'Set' in excel vba

Using this SO answer , i've been trying to get the following code to work.

' inserting formulas into the userOutput.csv sheet
    Dim wsUser As Worksheet:                Set wsUser = Worksheets("userOutput.csv")
    Dim agentEmailRange As Range:       'Set agentEmailRange = wsUser.Range(Cells(2, agentEmailColumn), Cells(propertyRows, agentEmailColumn))

     ' following line fails with runtime error 1004, method 'range' of object '_Worksheet' fialed.
     Set agentEmailRange = wsUser.Range(Cells(2, agentEmailColumn), Cells(propertyRows, agentEmailColumn))


            wsUser.Range("I1") = "Agent Email"

            With agentEmailRange
                .Value = "VLOOKUP(RC[-1], 'agentsOutput.csv'!R2C1:R" & agentRows & "C6 ,4, FALSE)"
            End With

the odd thing is it works one time. When I change one of the variables, however, it begins to fail.

How do I get that formula in the cells I need on a dynamic basis?

Try this one:

Dim wsUser As Worksheet
Dim agentEmailRange As Range

Set wsUser = Worksheets("userOutput.csv")

With wsUser
    Set agentEmailRange = .Range(.Cells(2, agentEmailColumn), .Cells(propertyRows, agentEmailColumn))
    .Range("I1") = "Agent Email"
End With

agentEmailRange.Formula = "=VLOOKUP(RC[-1], 'agentsOutput.csv'!R2C1:R" & agentRows & "C6 ,4, FALSE)"

You should fully qualify your Cells , ie specify to which sheet Cells belongs. Note that I'm using .Cells(..) instead Cells(..) - in that case Excel knows, that Cells belongs to sheet wsUser .

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