我有兩張表。片1包含下列數據使用Excel中的宏在循環中查找和替換
表1:
Column 1 column 2
Hotel A New York
Hotel B Melbourne
我希望以該值,以取代在片材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
和找到的話Name
和City
,並與我在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
任何提示或指導表示讚賞。
當'Name'是'Hotel A'或'Hotel B '? –
@RobinMackenzie'sheet 2'中的第一個'Name'是'hotel A',因爲它是'Sheet 1'中的第一行,第二個'Name'是'hotel B',因爲它是'sheet 1中的第二行'。換句話說,「Sheet 2」中的「Name」的數量等於「sheet 1」中的行數。 – MFR