替换多个单元格 [英] Replace multiple cells

查看:194
本文介绍了替换多个单元格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I'm looking for a way to simplify my code. Perhaps using an array if possible? Any assistance would be much appreciated.

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

现在你已经有一个方便的 MyVariables sub,您可以存储任何和所有全局变量。

Now that you've got a handy MyVariables sub, you can store any and all global variables there.

这篇关于替换多个单元格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆