VBA Resources For MS Word
2022-09-23
These are MS Word-specific VBA tips:
Sub CompressEmptyLines()
'
' CompressEmptyLines()
' This macro is a short-cut method to find and replace all occurrences of two side-by-side paragraph
' markers with a single paragraph marker. The macro operates on whatever text is currently selected.
'
With Selection.Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = "^p^p"
.Replacement.Text = "^p"
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
.Execute Replace:=wdReplaceAll
End With
End Sub
Sub ExportTableAsCSV()
' Export the currently selected table as a CSV file. This macro will
' create a new file that has the same name as the current document; except
' that the extension will be .csv, and store the CSV content version of
' the table in that file.
'
Dim numCols, numRows As Integer
Dim i, j As Integer
Dim cellText As String
Dim theTable As Range
Dim theFilename As String
Dim aCSVRow As String
Dim quotechar, quotedQuote As String
Dim rngTable As Range
quotechar = Chr(34)
quotedQuote = quotechar & quotechar & quotechar
theFilename = Left(ActiveDocument.FullName, _
InStrRev(ActiveDocument.FullName, ".") - 1) & ".csv"
Open theFilename For Output As #1
If Selection.Information(wdWithInTable) Then
'theTable = Selection.Tables(1).Range
' We're in a table, so proceed.
numCols = Selection.Tables(1).Columns.Count
numRows = Selection.Tables(1).Rows.Count
For i = 1 To numRows
aCSVRow = ""
For j = 1 To numCols
Set rngTable = Selection.Tables(1).Cell(i, j).Range
rngTable.MoveEnd Unit:=wdCharacter, Count:=-1
cellText = rngTable.Text
cellText = Replace(cellText, quotechar, quotedQuote)
If j = 1 Then
aCSVRow = quotechar & cellText & quotechar
Else
aCSVRow = aCSVRow & "," & quotechar & cellText & quotechar
End If
Next j
Print #1, aCSVRow
Next i
Close #1
End If
End Sub
Sub RemoveTrailingWhitespace()
'
' RemoveTrailingWhitespace()
' This macro uses find and replace to remove trailing whitespace from the end of all the
' paragraphs in a document. The macro operates on whatever text is currently selected.
'
With Selection.Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = "^w^p"
.Replacement.Text = "^p"
.Forward = True
.Wrap = wdFindContinue
.Format = False
.MatchCase = False
.MatchWholeWord = False
.MatchWildcards = False
.MatchSoundsLike = False
.MatchAllWordForms = False
.Execute Replace:=wdReplaceAll
End With
End Sub
See the page that linked to this one for other VBA resources I have found helpful.