VBA:如何从查找值的variables返回单元格引用?
首先,我对VBA很less有经验。 这是我的问题:
为了进行投资计算,我需要每天更新一定的汇率。 现在,我有一个button,一旦点击从网站自动带来一天的利率,我必须复制并粘贴到相应的date手动。 我想要做的只是点击button,费率将自动粘贴到其date旁边。 工作表如下所示:
Update Button Day's date Day's rate 03/01/2013 6% Date Rate 02/01/2013 5% 03/01/2013 6% 04/01/2013
最明显的方法是使用vlookup查找当天的date并将其粘贴到B列的正确位置,但问题是每次更新值时都会导致前一天的公式在一个错误。 所以最好的解决scheme是使用一个简单的macros来匹配A列中当天的date,并只粘贴它旁边的速率值。 用正常的工作表函数执行这个动作的一个好方法是=CELL("address";INDEX(B:B;MATCH($G$5;A:A;0);))
,这会导致问题是VBA中没有= CELL函数。
我试了下面的脚本,但没有成功:
Sub Teste2() Dim IndexFormula As Range MatchFormula = WorksheetFunction.Match(Range("Today"), Range("A:A"), 0) IndexFormula = WorksheetFunction.Index(Range("B:B"), MatchFormula, 0) Value = IndexFormula.Address Range("G5").Select Selection.Copy Value.Select Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _ :=False, Transpose:=False End Sub
我应该使用什么样的代码?
提前致谢
你非常接近你的尝试只是做一些小的变化,如下所示,它将工作,不需要使用一个发现,因为它会更慢:
Dim MatchFormula As Long Dim IndexFormula As Range MatchFormula = WorksheetFunction.Match(Range("Today"), Range("A:A"), 0) Set IndexFormula = WorksheetFunction.Index(Range("B:B"), MatchFormula, 0) IndexFormula.Value = Range("G5").Value
更重要的是,如果你希望它更快,你可以使用:
Dim MatchFormula As Long MatchFormula = WorksheetFunction.Match(Range("Today"), Range("A:A"), 0) Range("B" & MatchFormula).Value = Range("G5").Value
这是可行的,因为列上的匹配返回值与你的行,你可以只引用列B中的行,以无效使用索引的需要。
另一种select是使用查找function:
Sub Teste2() Dim res As Range Set res = Range("A:A").Find(What:=Range("Today"), Lookat:=xlWhole, MatchCase:=False) If Not res Is Nothing Then ' res.Offset(, 1) will give you column B (1 to the right from A) res.Offset(, 1).Value = Range("G5").Value End If End Sub
一些说明:
- 不要使用特定名称的variables,例如
Value
。 有一次你会被意想不到的结果所困惑 - 而是使用
Copy/PasteSpecial xlPasteValues
你可以使用Range("A1").Value = Range("B1").Value
- 避免在代码中使用Select / Active语句