2016-06-21 119 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