2016-06-21 60 views
2

我想寫一個宏,它在Excel表格中運行時會選擇一個特定的列,並且會用其他特定字符串的列表替換所有字符串列表的實例。例如,「string a1」的任何實例將被替換爲「string a2」,任何「string b1」替換爲「string b2」等。在excel中循環訪問字符串列表VBA

所以選擇列後,我需要運行

Selection.Replace What:="string a1", Replacement:="string a2", LookAt:=xlWhole  
Selection.Replace What:="string b1", Replacement:="string b2", LookAt:=xlWhole 
etc' 

現在我想創建一個循環這兩個表運行,但我無法弄清楚什麼樣的循環可以用於這個。
我將不勝感激有關如何從(隱藏)工作表中的列表或VBA模塊中定義的列表中執行此操作的建議。 非常感謝!

+0

你的意思是,你需要替換字符串的所有實例的數據集與大串B?或者你有兩列,需要用第一列替換第二列中的所有條目?你能否提供一個更清晰的數據例子,或許你已經嘗試了一些東西? –

+0

@F。 Stephen Q我會添加和編輯一些更多的信息 –

回答

1

我相信如何與大量單元交互的最快方式是將它們保存在內存中。

我個人會在字符串Dim sArray() as String列表,所有的字符串存儲在那裏之後,我會簡單地從第一個元素到最後循環像下面:

Dim iCounter as Long 

For iCounter = lbound(sArray) to UBound(sArray)-1 (based on the update below) 
    sArray(iCounter) = '...string manipulation logic here' 
Next iCounter 

編輯

我不太清楚你想要如何填充這個數組,但假設你的值在A1的單元格中到列A的最後一個單元格,那麼你可以執行以下操作:

'initialize initial array 
ReDim sArray(0 to 0) 

'now loop through the cells 
For iCounter = 1 to Range("A999999").End(XlUp).Row 
    If Range("A" & iCounter).value <> vbnullstring then 
     'we don't want to store empty strings, right? 
     sArray(UBound(sArray)) = Range("A" & iCounter).Value 
     ReDim Preserve sArray(0 to UBound(sArray)+1) 
    End If  
Next iCounter 
+0

請問您可以添加一個填充'sArray'列表的代碼示例嗎? –

1

把對一個隱藏的工作表,依次通過他們喜歡在此之後:

Dim r As Range 
Set r = [HiddenSheet!A1] 
Do Until IsEmpty(r.Value) 
    [MainSheet!A:A].Replace r.Value, r.Offset(0, 1).Value, xlWhole 
    Set r = r.Offset(1, 0) 
Loop