查找和替换数组的值,VBA

时间:2018-09-01 18:36:07

标签: arrays vba replace ms-word

假设我有一个像这样的数组:

Dim Arr() As Variant
arr(0)= "Text<&>data"
arr(1)= "<&>recombining"
arr(2)= "that libraries<&>"
arr(3)= "<&>professional<&>user "

我想在这些值内搜索并找到所有<&>,然后将其替换为and

.find的努力没有成功。 :(

2 个答案:

答案 0 :(得分:2)

使用Replace$。不确定是否要添加任何空格?我使用常量是因为您有固定的边界,因此在循环数组时不会调用UBoundLBound。另外,使用键入函数Replace$可以提高效率。

Option Explicit
Public Sub test()
    Const START_POINT As Long = 0
    Const END_POINT As Long = 3
    Dim Arr(START_POINT To END_POINT) As Variant, i As Long
    Arr(0) = "Text<&>data"
    Arr(1) = "<&>recombining"
    Arr(2) = "that libraries<&>"
    Arr(3) = "<&>professional<&>user "

    For i = START_POINT To END_POINT
        Arr(i) = Replace$(Arr(i), "<&>", "and")
    Next
    For i = START_POINT To END_POINT
        Debug.Print Arr(i)
    Next
End Sub

答案 1 :(得分:1)

您可以避免使用Join()循环将数组转换为字符串,进行替换,最后使用Split()将其转换回数组(未经测试):

Dim Arr As Variant
Arr = Array("Text<&>data", _
            "<&>recombining", _
            "that libraries<&>", _
            "<&>professional<&>user ")

Arr = Split(Replace$(Join(Arr, "|"), "<&>", "and"), "|")