【问题标题】:Search and Replace within Named Ranges - VBA for Excel在命名范围内搜索和替换 - VBA for Excel
【发布时间】:2018-09-28 06:36:16
【问题描述】:

我有一个包含大约一百个命名范围的 Excel 电子表格。我想运行一个脚本来查找这些命名范围内的某些字符串并将其替换为另一个字符串。问题在于更改命名范围的名称,同时保持底层单元格引用相同。

标准的 Excel 搜索和替换功能不适用于命名范围。

例如:命名范围 =“Turnover_Shop_ABC_2018”,我想将文本“Shop_ABC”替换为“Store_XYZ”。我需要搜索和替换一些字符串,但宏不需要很复杂:我不介意每次运行脚本并手动更新搜索字符串。

非常感谢任何帮助!

【问题讨论】:

    标签: excel vba search replace named


    【解决方案1】:

    这应该像遍历要更改的名称列表并执行此操作一样简单:

    ActiveWorkbook.Names("SomeName").Name = "SomeOtherName"
    

    这里有一个例程可以为你做到这一点:

    Option Explicit
    Option Compare Text
    
    Sub ReplaceNamePart(vMapping As Variant)
    Dim nm  As Name
    Dim sOld As String
    Dim sNew As String
    Dim i As Long
    
    
    For i = 1 To UBound(vMapping)
        sOld = vMapping(i, 1)
        sNew = vMapping(i, 2)
        For Each nm In ActiveWorkbook.Names
            If InStr(nm.Name, sOld) > 1 Then nm.Name = Replace(nm.Name, sOld, sNew)
        Next nm
    Next i
    
    End Sub
    

    ...您可以这样称呼它:

    Sub ReplaceNamePart_Caller()
    Dim v As Variant
    
    v = Range("NameChange").ListObject.DataBodyRange
    ReplaceNamePart v
    End Sub
    

    Caller sub 要求您将姓名更改映射放在 Excel 表格中,如下所示:

    ...并命名该表 NameChange:

    下面是运行代码之前的示例:

    ...结果如下:

    【讨论】:

    • 谢谢,但我不认为那会做我想要的。我需要在各种命名范围内搜索和替换字符串,而不是整个名称。
    • @BobsYourUncle 给你排序了吗?
    • 是的!这非常有效!非常感谢。这为我节省了数小时的繁琐工作@jeffreyweir
    【解决方案2】:

    您可以尝试使用输入框来输入字符串以进行查找和替换:

        Sub search_replace__string()
    
    Dim nm
    
    For Each nm In ActiveWorkbook.Names
    On Error Resume Next
    
    If nm.RefersToRange.Parent.Name <> ActiveSheet.Name Then GoTo thenextnamedrange
    
    MsgBox nm.Name
    
    With ThisWorkbook.ActiveSheet.Range(nm.Name)
    
    Dim i, j, FirstRow, FirstCol, LastRow, LastCol As Long
    Dim SelText, RepText, myStr As String
    
    FirstRow = .Row
    FirstCol = .Column
    LastRow = .End(xlDown).Row
    LastCol = .End(xlToRight).Column
    
     SelText = InputBox("Enter String", "Search for...")
     RepText = InputBox("Enter String", "Replace with...")
     If SelText = "" Then
     MsgBox "String not found"
     Exit Sub
     End If
     For j = FirstCol To LastCol
     For i = FirstRow To LastRow
     If InStr(Cells(i, j), SelText) Then
    
        myStr = Cells(i, j).Value
        Cells(i, j).Value = Replace(myStr, SelText, RepText)
    
     End If
     Next
     Next
    
    End With
    
    thenextnamedrange:
    Next nm
    
    End Sub
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-03-18
      • 2019-12-05
      • 2017-10-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多