使用此SO answer,我一直试图让以下代码正常运行。
' 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
奇怪的是它有效一次。但是,当我更改其中一个变量时,它开始失败。
如何在动态的基础上在我需要的单元格中获得该公式?
答案 0 :(得分:1)
试试这个:
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)"
您应该完全符合Cells
的资格,即指定Cells
所属的工作表。请注意,我使用.Cells(..)
代替Cells(..)
- 在这种情况下Excel知道,Cells
属于工作表wsUser
。