构建Word宏时,如何使用Visual Basic在表中查找特定的文本项?

时间:2015-04-09 16:47:05

标签: vba word-2007

我试图在表格单元格中找到所有单独的破折号并将它们居中。到目前为止,我在下面构建的内容将使文档中的所有破折号都居中。我怎样才能将它封装成仅以单元格中的破折号为中心?

 Sub Macro9()
  Selection.Find.ClearFormatting
  Selection.Find.Replacement.ClearFormatting
   With Selection.Find.Replacement.ParagraphFormat
    .SpaceBeforeAuto = False
    .SpaceAfterAuto = False
    .Alignment = wdAlignParagraphCenter
   End With

   With Selection.Find
    .Text = "-"
    .Replacement.Text = "-"
    .Forward = True
    .Wrap = wdFindContinue
    .Format = True
    .MatchCase = False
    .MatchWholeWord = False
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = False
  End With
  Selection.Find.Execute Replace:=wdReplaceAll
End Sub

2 个答案:

答案 0 :(得分:1)

由于您希望将搜索限制为单个单元格中的单个短划线,因此最好只检查单元格内容。否则,如果您在表格范围内使用.Find,则必须检查各种特殊情况,以确保单元格中的“找到”短划线完全独立。我认为这非常有效:

Option Explicit

Sub Macro9()
    Dim tbl As Table
    Dim tCell As Cell
    Dim r, c As Integer
    Dim cellContents As String

    For Each tbl In ActiveDocument.Tables
        For r = 1 To tbl.Rows.Count
            For c = 1 To tbl.Columns.Count
                Set tCell = tbl.Cell(r, c)
                '--- trim the cell delimiter off the end, then whitespace
                cellContents = Left(tCell.Range.Text, Len(tCell.Range.Text) - 2)
                cellContents = Trim(cellContents)
                If cellContents = "-" Then
                    tCell.Select
                    Selection.ParagraphFormat.Alignment = wdAlignParagraphCenter
                End If
            Next c
        Next r
    Next tbl

End Sub

答案 1 :(得分:0)

@PeterT您对此有何看法? (一位同事,我把它拉到一起)

Sub Macro1()

Dim CurrentText As Range
Selection.HomeKey Unit:=wdStory
Selection.Find.ClearFormatting
With Selection.Find
    .Text = "-"
    .Replacement.Text = ""
    .Forward = True
    .Wrap = wdFindContinue
    .Format = False
    .MatchCase = False
    .MatchWholeWord = False
    .MatchWildcards = False
    .MatchSoundsLike = False
    .MatchAllWordForms = False
End With
Do While Selection.Find.Execute

If Selection.Information(wdWithInTable) Then
    Set CurrentText = Selection.Cells(1).Range
    CurrentText.End = CurrentText.End - 1
    If (CurrentText.Text = "-") And Not (Selection.Information(wdAlignParagraphCenter)) Then
        Selection.ParagraphFormat.Alignment = wdAlignParagraphCenter
    End If
  End If
Loop      
End Sub