在Excel中使用macros查找和replace循环

我有两张床单。 工作表1包含以下数据

第1页:

Column 1 column 2 Hotel A New York Hotel B Melbourne 

我希望用这个值replace表2中的值

工作表2是这样的:

 Column 1 Column 2 Column 3 Name .... ..... ..... .... City .... .... .... Name .... ..... .... ..... City 

我的理想输出将是:

 Column1 Column 2 Column 3 Hotel A .... ..... ..... .... New York .... .... .... Hotel B .... ..... .... .... Melbourne 

因此,我希望在sheet 1查看一个循环,读取酒店的名称和城市,然后转到sheet 2 ,find“ Name和“ City ,并将其replace为sheet 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 

任何提示或指导表示赞赏。

Cells.Replace将会更改所有Replacement

您需要Find您正在Find的单元格,然后replace该单元格中的值:

 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 

这应该工作。 循环searchsht1中的每个Name和City,并replacesht2的“A”和“C”列中的第一个匹配项:

 Sub testLoopPaste() Dim i As Long Dim wb As Workbook Dim sht1 As Worksheet, sht2 As Worksheet Set wb = ThisWorkbook Set sht1 = wb.Sheets("Sheet1") Set sht2 = wb.Sheets("Sheet2") Dim Loc As Range For i = 1 To sht1.Range("A" & sht1.Rows.Count).End(xlUp).row Set Loc = sht2.Columns(1).Find(What:="Name") If Not Loc Is Nothing Then Loc.Value = sht1.Cells(i, "A") Set Loc = sht2.Columns(3).Find(What:="City") If Not Loc Is Nothing Then Loc.Value = sht1.Cells(i, "B") Next i End Sub