简体   繁体   English

在Excel VBA中使用“设置”设置范围

[英]setting ranges using 'Set' in excel vba

Using this SO answer , i've been trying to get the following code to work. 使用这个SO答案 ,我一直在尝试使以下代码起作用。

' 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. 您应该完全限定Cells ,即指定Cells所属的表。 Note that I'm using .Cells(..) instead Cells(..) - in that case Excel knows, that Cells belongs to sheet wsUser . 请注意,我使用的是.Cells(..)而不是Cells(..) -在这种情况下,Excel知道Cells属于表wsUser

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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