【发布时间】:2012-08-13 22:50:11
【问题描述】:
我正在尝试在工作表中搜索某个值,在本例中为“ALAE”。找到这个实例后,我需要继续下去,用另一个工作表上的参考值替换所有后续字段。
例如,字段以“ALAE”作为列标题,然后在其下方有两个“2”。我需要去参考表,查找 2 的含义,并将值替换为文本版本。 “ALAE”的位置总是会改变,标题下方的字段数量也是如此。每次运行宏时,我都需要动态地执行此操作。
目前,代码将替换第一个“2”,但不会替换第二个。
这是我目前的代码
Sub Reference()
Dim macroSheet As Worksheet
Dim LastRow As Long
Dim strSearch As String
Dim aCell As Range, bCell As Range
Dim x As Integer
Set macroSheet = Sheets("Treaty Year Preview")
With macroSheet
LastRow = .Range("A" & Rows.Count).End(xlUp).Row
strSearch = "ALAE"
Set aCell = .Range("A1:R" & LastRow).Find(What:=strSearch, LookIn:=xlValues, _
Lookat:=xlWhole, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=True, SearchFormat:=False)
If Not aCell Is Nothing Then
x = 1
Set bCell = aCell
Do
aCell.Offset(x) = Application.WorksheetFunction.VLookup(aCell.Offset(x), Worksheets("ALAE ULAE").Range("A:B"), 2)
x = x + 1
Loop Until aCell.Offset(x) Is Nothing
End If 'If Not aCell is Nothing Then
End With 'With macroSheet
End Sub
【问题讨论】:
-
我看到的第一件事是
Set getRow = ActiveCell.Row因为整数变量不是对象,所以您不需要设置它。只需写getRow = replaceCell.Row。此外,lookup = Selection.Value谁知道您当前的选择是什么,因为您从未告诉宏选择任何内容。 Find 可能会以这种方式工作(我忘记了),但你最好写lookup = aCell.Value或lookup = replaceCell.Value不确定你想要哪个。除非绝对必要,否则最好避免使用ActiveCell和Selection。他们经常欺骗你! -
非常感谢您的快速回复和有用的信息,斯科特!你不知道我当前的选择是什么,这行是否: Set replaceCell = aCell.Offset(1, 0).Select 使它被选中?
-
我刚刚编辑了我的 cmets。请再读一遍。另外,让我们知道这是否解决了它! (可能不会)
-
是的。之后我注意到了。我即将回复一个可以清理您的代码并为您提供所需的答案。我会评论它来解释。
-
我现在在查找函数中遇到语法错误:
lookup = macroSheet.Application.WorksheetFunction.Lookup(lookup, ALAE!C[getRow], ALAE!B[getRow])并且在子标题中传递的变量不正确:\