lundi 20 avril 2015

Multdimensional array in VBA for Microsoft Word on Mac

I'm working on a macro to loop through a series of strings (a1, a2, a3) and replace them with a series of corresponding values (b1, b2, b3). I've created an array to store the strings to match:

Dim search_strings(1 To 2) As String
search_strings(1) = "match1"
search_strings(2) = "match2"

I can loop through this array with a For Each loop. But I can't figure out how to store and reference the corresponding replacement text. I know that I need some sort of key/value pair. I've tried using a dictionary, like this:

Dim dict As New Scripting.Dictionary
dict.Add "match", "replace"

But for that to work, I need to reference Microsoft Scripting Runtime, which isn't available on Mac OS X. (Currently, I get this error: Compile error: User-defined type not defined.)

Is there another way?

Here's the full code:

Sub MyMacro()
    ' Initialize variables
    Dim search_strings(1 To 2) As String
    Dim this_search_string As Variant
    Dim myRange As Range
    Dim Reply As Integer
    ' Define strings to match
    search_strings(1) = "match1"
    search_strings(2) = "match2"
    ' Run a search for each string in the array of strings to match
    For Each this_search_string In search_strings
        ' Define the search range to be the whole document
        Set myRange = ActiveDocument.Content
        ' Set the Find parameters
        myRange.Find.ClearFormatting
        myRange.Find.MatchWildcards = True
        ' Loop through each match in the document
        Dim cached As Long
        cached = myRange.End
        Do While myRange.Find.Execute(this_search_string)
            myRange.Select
            ' Prompt the user to replace the match
            Reply = MsgBox("Replace '" & myRange.Find.Text & "'?", vbYesNoCancel)
            If Reply = 6 Then ' "Yes" clicked
                myRange.Text = "replacement"
            ElseIf Reply = 2 Then ' "Cancel" clicked
                Exit Do
            End If
            myRange.Start = myRange.Start + Len(myRange.Find.Text)
            myRange.End = cached
        Loop
    Next this_search_string
End Sub

Aucun commentaire:

Enregistrer un commentaire