Vba 替换多个单元格

Vba 替换多个单元格,vba,excel,replace,Vba,Excel,Replace,我正在寻找一种简化代码的方法。如果可能的话,也许使用数组?任何帮助都将不胜感激 Cells.Replace What:="Invoice EMEA Payment", Replacement:="Invoice", LookAt:=xlWhole On Error Resume Next Cells.Replace What:="Invoice EMEA No Payment", Replacement:="Invoice", LookAt:=xlWhole On Error Resume Ne

我正在寻找一种简化代码的方法。如果可能的话,也许使用数组?任何帮助都将不胜感激

Cells.Replace What:="Invoice EMEA Payment", Replacement:="Invoice", LookAt:=xlWhole
On Error Resume Next
Cells.Replace What:="Invoice EMEA No Payment", Replacement:="Invoice", LookAt:=xlWhole
On Error Resume Next
Cells.Replace What:="Invoice USA Payment", Replacement:="Invoice", LookAt:=xlWhole
On Error Resume Next
Cells.Replace What:="Invoice USA No Payment", Replacement:="Invoice", LookAt:=xlWhole
On Error Resume Next
Cells.Replace What:="Invoice1 Lite EMEA Payment", Replacement:="Invoice1 Lite", LookAt:=xlWhole
On Error Resume Next
Cells.Replace What:="Invoice1 Lite EMEA No Payment", Replacement:="Invoice1 Lite", LookAt:=xlWhole
On Error Resume Next
Cells.Replace What:="Invoice1 Lite USA Payment", Replacement:="Invoice1 Lite", LookAt:=xlWhole
On Error Resume Next
Cells.Replace What:="Invoice1 Lite USA No Payment", Replacement:="Invoice1 Lite", LookAt:=xlWhole
On Error Resume Next
试试这个:

Option Explicit

Global ReplaceText(8, 2) As String ' <~ set up a global array of strings and replacements

'build out all of our global constants here
Sub MyVariables()
    ReplaceText(1, 1) = "Invoice EMEA Payment"
    ReplaceText(1, 2) = "Invoice"
    ReplaceText(2, 1) = "Invoice No EMEA Payment"
    ReplaceText(2, 2) = "Invoice"
    ReplaceText(3, 1) = "Invoice USA Payment"
    ReplaceText(3, 2) = "Invoice"
    ReplaceText(4, 1) = "Invoice USA No Payment"
    ReplaceText(4, 2) = "Invoice"
    ReplaceText(5, 1) = "Invoice1 Lite EMEA Payment"
    ReplaceText(5, 2) = "Invoice1 Lite"
    ReplaceText(6, 1) = "Invoice1 Lite EMEA No Payment"
    ReplaceText(6, 2) = "Invoice1 Lite"
    ReplaceText(7, 1) = "Invoice1 Lite USA Payment"
    ReplaceText(7, 2) = "Invoice1 Lite"
    ReplaceText(8, 1) = "Invoice1 Lite USA No Payment"
    ReplaceText(8, 2) = "Invoice1 Lite"
End Sub

'implement the find and replace
Sub FindAndReplace()

Dim Idx As Long
Dim MySheet As Worksheet

Call MyVariables ' <~ call the MyVariables sub and boom, you've got the ReplaceText array

Set MySheet = ThisWorkbook.ActiveSheet
With MySheet
    For Idx = 1 To UBound(ReplaceText)
        .Cells.Replace What:=ReplaceText(Idx, 1), _
            Replacement:=ReplaceText(Idx, 2), LookAt:=xlWhole
    Next Idx
End With

End Sub
选项显式

Global ReplaceText(8,2)As String'您可以将这些建立良好的字符串包装在存储在全局类型子中的
字符串
数组中,然后对其进行迭代。。。将这种可重复和可重用的信息存储在全局子系统中可以节省大量时间。