简体   繁体   中英

Preserving table selection in Word 2003 VBA macro

My goal is to write a VBA Macro for Word 2003, where the user selects part of a table (especially a column), and the macro maps input characters to specific output characters, eg any of aeiou become V ; some sequences like eh uw become V ; one character (exclamation mark) is deleted; anything not turned into "V" is turned into "C". My problem is that after the first replace, the selection gets "unset", so changes affect something other than the original selection.

    With Selection.Find
            .ClearFormatting
            .Replacement.ClearFormatting
            .MatchWildcards = True
            .Replacement.Text = "V"
            .Text = "[aeiouáéíóú]"
            .Execute Replace:=wdReplaceAll
'replace certain sequences
            .Text = "[mn" & ChrW(618) & ChrW(650) & "]" & ChrW(769)
            .Execute Replace:=wdReplaceAll
            .Text = "[mn]" & ChrW(768)
            .Execute Replace:=wdReplaceAll
'delete !
            .Text = "[\!]"
            .Replacement.Text = ""
            .Execute Replace:=wdReplaceAll
'everything else becomes C
            .Text = "[!V]"
            .Replacement.Text = "C"
            .Execute Replace:=wdReplaceAll
    End With

How do you get find/replace to only operate on the selected cells? I notice that after the first replace, Selection.End changes to the same value as Selection.Start. I do not understand how column selection works in Word.

I created some macros to facilitate this. This will start an answer on how to move around columns.

Sub GoToTop()
ActiveWindow.ActivePane.View.SeekView = wdSeekMainDocument      ' This takes the pointer to the body of the document ' place cursor the body of the document in case you are located on the header
Selection.EndKey Unit:=wdStory 'key ctrl end
Selection.HomeKey Unit:=wdStory 'key ctrl end
End Sub


Sub GoToColumnTable() 'place cursor inside of the first column
    Selection.GoTo What:=wdGoToTable
End Sub

Sub ColumnMove() 'move from one column to the other one
    Selection.Move Unit:=wdColumn, Count:=1
End Sub
Sub ColumnSelect() 'select the entire column in which the cursor is
    Selection.SelectColumn
End Sub
Sub ColumnDelete() 'delete a column that was selected
    Selection.Columns.Delete
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM