Word VBA - 将选择替换为数组中的下一项

时间:2015-12-28 14:45:50

标签: arrays ms-word word-vba

我想反复点击我的宏,用我的数组中的单词替换我选择的单词。

这是我想要做的:

  1. 如果Selection = BeingSArray或BeingArray中的单词

  2. 然后用BeingArray

  3. 中的第一个/下一个单词替换Selection
  4. 当我再次运行宏时,它应该用BeingArray中的第二个/下一个单词替换新单词,依此类推(在循环中)

  5. 这是我失败的尝试之一:

    With Selection
    
        BeingSArray("am ", "is ", "are ", "was ", "were ", "be ", "being ", "been ") 'I have a separate list here because, when I highlight a word, I may have the following space highlighted with it. 
    
        BeingArray("am", "is", "are", "was", "were", "be", "being", "been")
    
        If .Text = BeingArray(1) or .Text = BeingSArray(1) Then .TypeText = BeingArray(2)
    
        'Do I need to add a command to select the new word here?
    
        If .Text = BeingArray(2) Or .Text = BeingSArray(2) Then .TypeText = BeingArray(3) 'and so on
    
        If .Text = BeingArray(8) Or .Text = BeingSArray(8) Then .TypeText = BeingArray(1)
    
    End With
    

1 个答案:

答案 0 :(得分:1)

首先,VBA没有内置函数来查找数组中项目的位置,因此您必须自己编写。试试这个:

Function IndexOf(arr As Variant, value, ByRef found As Boolean) As Integer
    Dim lb As Integer, ub As Integer, i As Integer
    found = False
    If Not IsArray(arr) Then Exit Function
    lb = LBound(arr)
    ub = UBound(arr)
    For i = lb To ub
        If arr(i) = value Then
            found = True
            IndexOf = i
            Exit Function
        End If
    Next
End Function

此功能使用如下:

Dim found As Boolean

'prints 0 and False -- first argument is not an array
Debug.Print IndexOf("test", "test", found) 
Debug.Print found

Dim testArray As Variant
testArray = Array("The", "rain", "in", "Spain", "falls", "mainly", "on", "the", "plain")

'prints 0 and False -- "Portugal" is not in the array
Debug.Print IndexOf(testArray, "Portugal", found)
Debug.Print found

'prints 6
Debug.Print IndexOf(testArray, "on", found)
Debug.Print found 'prints True

一旦你有了这样的功能:

Dim BeingArray, text As String, found as Boolean
Dim index As Integer, nextIndex as Integer

BeingArray = Array("am", "is", "are", "was", "were", "be", "being", "been")
text = Trim(Selection.Text) 'this is simpler than creating a separate array
index = IndexOf(BeingArray, text, found)
If found Then
    nextIndex = (index + 1) % UBound(BeingArray)
    Selection.Text = BeingArray(nextIndex)
End If