Vba 使用Excel中的宏在循环中查找和替换
我有两张床单。表1包含以下数据 第1页:Vba 使用Excel中的宏在循环中查找和替换,vba,excel,Vba,Excel,我有两张床单。表1包含以下数据 第1页: Column 1 column 2 Hotel A New York Hotel B Melbourne Column 1 Column 2 Column 3 Name .... ..... ..... .... City .... .... .... Name .... ..... .... ...
Column 1 column 2
Hotel A New York
Hotel B Melbourne
Column 1 Column 2 Column 3
Name .... .....
..... .... City
.... .... ....
Name .... .....
.... ..... City
我希望用这个值替换表2中的值
第2页是这样的:
Column 1 column 2
Hotel A New York
Hotel B Melbourne
Column 1 Column 2 Column 3
Name .... .....
..... .... City
.... .... ....
Name .... .....
.... ..... City
我的理想输出是:
Column1 Column 2 Column 3
Hotel A .... .....
..... .... New York
.... .... ....
Hotel B .... .....
.... .... Melbourne
因此,我希望在表1
中进行循环,阅读酒店的名称和城市,然后进入表2
,找到名称
和城市
,并用表1
中的内容替换它们。我是VBA的新手,我的代码就是这样开始的,它甚至会循环。为什么会这样
Sub testLoopPaste()
Dim j, k, L, b As String
Dim i As Long
Dim wb As Workbook
Dim sht1 As Worksheet
Dim sht2 As Worksheet
Set wb = ThisWorkbook
Set sht1 = wb.Sheets("Sheet1")
Set sht2 = wb.Sheets("Sheet2")
j = "Name"
b = "City"
For i = 1 To 2
k = sht1.Range("A" & i)
L = sht1.Range("B" & i)
sht2.Cells.Replace what:=j, replacement:=k, lookat:=xlWhole, MatchCase:=False
sht2.Cells.Replace what:=b, replacement:=L, lookat:=xlWhole, MatchCase:=False
Next i
End Sub
任何提示或指导都将不胜感激
单元格。替换
将使用替换
更改所有出现的内容
您需要找到要查找的单元格,然后仅替换该单元格中的值:
Sub testLoopPaste()
'Note: existing code was declaring j, k and L as Variant
Dim j As String, k As String, L As String, b As String
Dim i As Long
Dim wb As Workbook
Dim sht1 As Worksheet
Dim sht2 As Worksheet
Dim found As Range
Set wb = ThisWorkbook
Set sht1 = wb.Sheets("Sheet1")
Set sht2 = wb.Sheets("Sheet2")
j = "Name"
b = "City"
For i = 1 To 2
' always advisable to specify .Value rather than assuming it will be the default property
k = sht1.Range("A" & i).Value
L = sht1.Range("B" & i).Value
Set found = sht2.Cells.Find(What:=j, _
LookIn:=xlValues, _
LookAt:=xlWhole, _
After:=sht2.Cells(sht2.Rows.Count, sht2.Cells.Count), _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False, _
SearchFormat:=False)
If Not found Is Nothing Then
found.Value = k
End If
Set found = sht2.Cells.Find(What:=b, _
LookIn:=xlValues, _
LookAt:=xlWhole, _
After:=sht2.Cells(sht2.Rows.Count, sht2.Cells.Count), _
SearchOrder:=xlByRows, _
SearchDirection:=xlNext, _
MatchCase:=False, _
SearchFormat:=False)
If Not found Is Nothing Then
found.Value = L
End If
Next i
End Sub
这应该行得通。循环搜索sht1中的每个名称和城市,并替换sht2的“A”列和“C”列中的第一个匹配项:
你怎么知道名称是酒店A
还是酒店B
?@RobinMackenzie第2张中的第一个名称
是酒店A
,因为它是第1张中的第一行,第二个名称是酒店B
,因为它是第二行1
。换句话说,第2张
中的名称
的数量等于第1张
中的行数。我测试了代码。酒店A和酒店B最终处于相反的位置。城市是正确的。@June7-我很担心-我希望你的标题在第一排,因此第一场比赛不会在A1牢房。给我几分钟,我会更新答案,开始搜索单元格(Rows.Count,Columns.Count)。@June7-好-我已强制查找
从工作表上的最后一个单元格开始。这样,如果第一个匹配项在单元格A1中,它仍然会找到它。