excel - 在 Excel VBA 中循环字符串列表

标签 excel loops vba

我正在尝试编写一个宏,当在 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/

相关文章:

excel - 如何每第n行插入函数的值

excel - Excel 中的字符串操作

excel - 在 Outlook 电子邮件中粘贴 Excel 表格 : it looks back

Python 仅显示 .csv 文件的最后一行

vba - 用VBA破解Sheet密码

java - 有没有办法在数组的 foreach 循环中创建对象

vba - 退出 Excel 时忽略 "Do you wish to save"框

java - 如何让程序在异常后继续运行?

php - 使用循环创建 MySQL 查询

vba - Application.ScreenUpdating 停止 VBA 中的宏执行