2014-04-07 78 views
0

使用此SO answer,我一直在試圖讓下面的代碼工作。設置範圍使用'設置'在excel vba

' 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 

奇怪的是它有一次工作。但是,當我更改其中一個變量時,它開始失敗。

如何在動態基礎上獲取需要的單元格中的公式?

回答

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