【问题标题】:difficultly vba find replacevba 很难找到替换
【发布时间】:2016-09-01 17:45:36
【问题描述】:

如果我当前的方法是最好的,我有点困惑,但我有 excel 文件,其中第一行有不同的列标题,具体取决于我从谁那里得到它们。我正在尝试标准化第 1 行中的标题。

我将如何编写一个脚本来查找,比如说:

find = "clname" or "first name" or "full name"
替换=“名称”

find =“地址”或“adr”或“位置”
替换 = "Cl_Adress"

我需要做大约 15 次不同的查找和替换。有没有更好的方法来做到这一点。我目前正在使用这个脚本。

Sub findrep()
    Dim i As String
    Dim k As String

    i = "Find"
    k = "Text to replace"
    Rows(1).replace what:=i, replacement:=k, lookat:=xlPart, MatchCase:=False
End Sub

【问题讨论】:

  • 你确定要lookat:=xlPart吗?在我看来,列标题标签应该是整个单元格内容。

标签: vba excel replace find


【解决方案1】:

我会使用正则表达式。设置对“Microsoft VBScript 正则表达式 5.5”的引用,然后循环遍历第一行中的列

Sub ReplaceMultipleItems() Dim rx1 作为新的正则表达式 Dim rx2 作为新的正则表达式 将 intColCount 调暗为整数 将 intColCounter 调暗为整数

intColCount = ActiveSheet.UsedRange.Columns.Count

rx1.Pattern = "clname|first name|full name"
rx2.Pattern = "address|adr|location"

For intColCounter = 1 To intColCount
    ActiveSheet.Cells(1, intColCounter).Value = _
    rx2.Replace(rx1.Replace(ActiveSheet.Cells(1, intColCounter).Value, "Name"), "Cl_Adress")
Next intColCounter

结束子

【讨论】:

    【解决方案2】:

    使用大小相等的两个变体数组;一个用于what:= 值,另一个用于replacement:= 值。循环遍历它们以完成替换。

    Sub blahblah()
        Dim v As Long, fnd As Variant, rpl As Variant
    
        fnd = Array("clname", "first name", "full name", _
                    "address", "adr", "location")
        rpl = Array("name", "name", "name", _
                    "Cl_Adress", "Cl_Adress", "Cl_Adress")
    
        With Worksheets("Sheet1")
            With .Rows(1)
                For v = LBound(fnd) To UBound(fnd)
                    .Replace what:=fnd(v), replacement:=rpl(v), _
                             MatchCase:=False, lookat:=xlWhole
                Next v
            End With
        End With
    End Sub
    

    【讨论】:

      猜你喜欢
      • 2014-05-15
      • 2018-10-06
      • 2013-04-01
      • 2012-03-08
      • 2018-04-11
      • 2013-07-15
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多