2016-12-31 89 views
0

我想要一個代碼來查找並替換Excel表格的第一行中的所有單元格。我有以下代碼搜索谷歌。Excel:查找並替換excel表格的第一行

Sub FindReplace() 

Dim sht As Worksheet 
Dim fndList As Variant 
Dim rplcList As Variant 
Dim x As Long 

fndList = Array("Fname", "Lname", "Phone") 
rplcList = Array("First Name", "Last Name", "Mobile") 

For x = LBound(fndList) To UBound(fndList) 
    For Each sht In ActiveWorkbook.Worksheets 
     Rows(1).Replace What:=fndList(x), Replacement:=rplcList(x), _ 
       LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _ 
       SearchFormat:=False, ReplaceFormat:=False 
    Next sht 
Next x 

End Sub 

這工作正常。但我們應該在代碼本身中提及查找和替換列表。如何讓它從用戶端獲取輸入,而不是在代碼中手動輸入。作爲文本或文件輸入會很好。

+0

要從用戶輸入使用'Inputbox'方法。 – newguy

+0

可以請給我一段代碼。我不知道如何編碼,我敢肯定,我會在巨大的錯誤... –

+0

我有一個大的清單來取代。 'Inputbox'會支持多重迭代嗎? –

回答

3
fndList = Split(Application.InputBox("List the values to be searched for in the following format: " & vbCrLf & "val1, val2, val3, ...", Type:=2), ",") '<--| this returns an array of 'String's 
rplcList = Split(Application.InputBox("List the values to be replaced in the following format: " & vbCrLf & "val1, val2, val3, ...", Type:=2), ",") '<--| this returns an array of 'String's 

For Each sht In ActiveWorkbook.Worksheets 
    For x = LBound(fndList) To UBound(fndList) 
     sht.Rows(1).Replace What:=fndList(x), Replacement:=rplcList(x), _ 
         LookAt:=xlPart, SearchOrder:=xlByRows, MatchCase:=False, _ 
         SearchFormat:=False, ReplaceFormat:=False 
    Next x 
Next sht 
+0

嗨,謝謝你的代碼。但它只是更新我的A1單元格。我給輸入Fname,Lname,電話和Fisrtname,姓,手機。我在這裏犯了什麼錯誤嗎? –

+0

看到編輯答案。如果它解決了您的問題,請將其標記爲已接受。謝謝。 – user3598756

+0

我仍然得到相同的結果。只有「A1」單元正在更新。 –