2016-12-31 36 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”单元正在更新。 –