在命名范围内搜索和替换- VBA for Excel

velaa5lx  于 2023-05-30  发布在  其他
关注(0)|答案(2)|浏览(174)

我有一个Excel电子表格,里面有大约一百个命名范围。我想运行一个脚本来查找这些命名范围内的某些字符串,并将其替换为另一个字符串。问题在于更改命名范围的名称,同时保持基础单元格引用不变。
标准的Excel搜索和替换功能不适用于命名范围。
例如:Named range =“Turnover_Shop_ABC_2018”,我想用“Store_XYZ”替换文本“Shop_ABC”。有几个字符串我需要搜索和替换,但宏不需要很复杂:我不介意每次运行脚本并手动更新搜索字符串。
任何帮助非常感谢!

iyzzxitl

iyzzxitl1#

这应该很简单,只需迭代要更改的名称列表并执行以下操作:

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

调用者子程序要求您将名称更改Map放入Excel表中,如下所示:

...并将其命名为Table NameChange:

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

结果是这样的

lvjbypge

lvjbypge2#

你可以尝试用输入框输入字符串来查找和替换:

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

相关问题