【问题标题】:Excel VBA Replace with Array GroupsExcel VBA 替换为数组组
【发布时间】:2015-05-23 10:01:33
【问题描述】:

现在我正在使用一种效率极低的替换功能:

Dim Replacement As String
Dim rngRepVal As Object

Set rngRepVal = Sheets("data").Range(Cells(1, 3), Cells(intRowLast, 3))
Replacement = ActiveCell.Value
rngRepVal.Replace What:="123", Replacement:="ABC", LookAt:=xlWhole, SearchOrder:=xlByRows, MatchCase:=False
rngRepVal.Replace What:="234", Replacement:="ABC", LookAt:=xlWhole, SearchOrder:=xlByRows, MatchCase:=False
rngRepVal.Replace What:="456", Replacement:="DEF", LookAt:=xlWhole, SearchOrder:=xlByRows, MatchCase:=False
... [goes on for 50 lines]
Set rngRepVal = Nothing

我想知道这是否可以通过数组来实现。比如:

Dim aWhat() As String
Dim aReplacement() As String

aWhat = Split("ABC|DEF|GHI|JKL", "|")
aReplacement = Split(Array("123", 456")|Array("789","1000"), "|") '<-not sure how to organise this

在替换循环中,基本上 123 和 456 被 ABC 替换,789 和 1000 被 DEF 等替换> 关于如何组织这两个数组的任何见解?谢谢!

【问题讨论】:

    标签: arrays excel vba replace


    【解决方案1】:

    我想是偶然发现的:

    Dim aOld() As Variant
    Dim aNew() As Variant
    Dim Group As Variant
    Dim Word As Variant
    Dim y As Long
    
    aNew = Array("ABC", "DEF", "GHI", "JKL")
    aOld = Array(Array("123", "456"), Array("789", "1000"))
    
    With Range("A:A")
        For Each Group In aOld
            For Each Word In Group
                .Replace What:=Word, Replacement:=aNew(y), LookAt:=xlWhole, SearchOrder:=xlByRows, MatchCase:=False
            Next
        y = y + 1
        Next
    End With
    

    【讨论】:

      【解决方案2】:

      我会试试这个:

      aWhat=Split("ABC|ABC|DEF|DEF|GHI|GHI...","|")
      aReplacement=Split("123|456|789|.....","|")
      For i=1 to UBound(aWhat)
        rngRepVal.Replace what:=aWhat[i], Replacement:=aReplacement[i], ....
      Next i
      

      只需确保两个数组中的元素数量相同。

      【讨论】:

        【解决方案3】:

        您的Replace(s) 很好 - 它的逐个单元循环和选择效率低下。尝试这样的方法一次在整个范围内进行三个替换。

        Sub Recut()
        Dim rng1 As Range
        Set rng1 = Sheets("data").Range(Sheets("data").Cells(1, 3), Sheets("data").Cells(Rows.Count, 3).End(xlUp))
        With rng1
            .Replace What:="123", Replacement:="ABC", LookAt:=xlWhole, SearchOrder:=xlByRows, MatchCase:=False
            .Replace What:="234", Replacement:="ABC", LookAt:=xlWhole, SearchOrder:=xlByRows, MatchCase:=False
            .Replace What:="456", Replacement:="DEF", LookAt:=xlWhole, SearchOrder:=xlByRows, MatchCase:=False
        End With
        End Sub
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2015-03-18
          • 2015-05-22
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-03-14
          • 2018-12-15
          相关资源
          最近更新 更多