将公式中的单元格地址作为变量提供

时间:2018-02-08 16:54:31

标签: vba excel-vba excel

我正在尝试使用VBA从数据转储中提取信息。我的方法是找到触发器字符串并从作为搜索结果激活的单元格中提取信息。

Sub ExtractingValues_T1()
Dim ValueLoc As String

Sheets("Sheet1").Select 'This is to select the right sheet
Range("A1").Select 'This is so that when I perform my find, I get results top down

Cells.Find(What:="037 = 2001", After:=ActiveCell, LookIn:=xlFormulas, _
    LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
    MatchCase:=False, SearchFormat:=False).Activate 'This simply selects the first cell that meets my search requirement

'Below is where I run into trouble
ValueLoc = ActiveCell.Address 'Here, I'm trying to get the address of the cell I need to use a formula on
Sheets("Sheet2").Range("C2").Formula = "=RIGHT(ActiveCell, 10)" 'Here I try to use that address in the formula

但是,我收到了一个错误。我理解我的问题是我的方法,我不能提供单元格引用作为我正在做的方式的变量。但是正确的方法是什么?

1 个答案:

答案 0 :(得分:1)

如下所示略有不同,你应该尽量不要使用Select&激活方法,因为它们非常不守规矩,你可能会得到不想要的结果,下面的代码将完成你所期望的而不选择任何东西:

Sub ExtractingValues_T1()
Dim foundvalue As Range
'below specified Sheet and Range to look for the value, in this case looking in Column A, amend as required
Set foundvalue = Sheets("Sheet1").Range("A:A").Find(What:="037 = 2001", After:=Sheets("Sheet1").Range("A1"), LookIn:=xlFormulas, _
    LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
    MatchCase:=False, SearchFormat:=False)

If Not foundvalue Is Nothing Then 'if you found something
    Sheets("Sheet2").Range("C2").Formula = "=RIGHT(" & foundvalue.Address & ", 10)" 'add the address of the found value
End If

End Sub