【问题标题】:Excel: Find and replace first row of and excel sheetExcel:查找并替换 Excel 工作表的第一行
【发布时间】:2023-04-06 02:39:01
【问题描述】:

我想要一个代码来查找和替换 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

这很好用。但我们应该在代码本身中提到查找和替换列表。如何使其从用户端获取输入,而不是在代码中手动输入。作为文本或文件输入会很好。

【问题讨论】:

  • 从用户那里获取输入,使用Inputbox方法。
  • 能否给我一段代码。我不知道如何编码,我相信我最终会出现巨大的错误......
  • 我有一个大列表要替换。 Inputbox 会支持多次迭代吗?

标签: excel replace find vba


【解决方案1】:
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

【讨论】:

  • 您好,感谢您提供代码。但它只是更新我的 A1 单元格。我正在输入 Fname、Lname、Phone 和 Fisrtname、Lastname、Mobile。我在这里做错了吗?
  • 我仍然得到相同的结果。只有“A1”单元格正在更新。
  • 这是因为前导空格:要么将输入格式从"val1, val2, val3, ..."更改为"val1,val2,val3, ..."(即您要求用户不要输入空格 在每个定界逗号之后)或者你 Trim() fndList(x)rplcList(x)(即 sht.Rows(1).Replace What:=Trim(fndList(x)), Replacement:=Trim(rplcList(x)), _...
  • 您的代码没有 space 可以正常工作。 Trim() 函数给我Compile error: Wrong number of arguments or invalid property assignment
  • 它对我有用:你必须用代码中已有的内容替换最后的 ...
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2015-05-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-03-18
  • 2017-01-22
  • 2018-04-11
相关资源
最近更新 更多