我正在尝试编写一个宏,当在 Excel 工作表中运行时,该宏将选择一个特定列,并将用其他特定字符串列表替换字符串列表的所有实例。例如,“字符串 a1”的任何实例都将替换为“字符串 a2”,任何“字符串 b1”将替换为“字符串 b2”,等等。
所以选择列后我需要运行
Selection.Replace What:="string a1", Replacement:="string a2", LookAt:=xlWhole
Selection.Replace What:="string b1", Replacement:="string b2", LookAt:=xlWhole
etc'
现在我想创建一个循环来遍历这两个列表,但我不知道可以使用哪种循环。
我希望得到有关如何从(隐藏)工作表中的列表或从 VBA 模块中定义的列表执行此操作的建议。
非常感谢!
最佳答案
我相信与大量细胞交互的最快方法是将它们保存在内存中。
我个人会将所有字符串存储在字符串列表中 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
关于excel - 在 Excel VBA 中循环字符串列表,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37950040/