0

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?

Community
  • 1
  • 1
DBWeinstein
  • 8,605
  • 31
  • 73
  • 118

1 Answers1

1

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, i.e. 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.

Dmitry Pavliv
  • 35,333
  • 13
  • 79
  • 80