【问题标题】:Selection.Find within a rangeSelection.Find 在一个范围内
【发布时间】:2019-01-31 05:20:25
【问题描述】:

我不熟悉 Word VBA,并且在使用 Selection.Find 时遇到了问题。

我想用小数点替换表格中一系列单元格中的逗号。但是,我只能让 Selection.Find 替换文档中的所有逗号或仅替换范围中的第一个逗号。

我想要的是 Excel 中的 Selection.Replace What:=".", Replacement:=",",但 Word 不支持。

非常感谢您的建议!

CJ

Sub Replace_Percent_Separator()
'Correct percent separator in row 6, table 2

Dim PcentCells As Range

Path = "C:\xxx\Word\"
file = Dir(Path & "*.docx")

Application.DisplayAlerts = False
Application.ScreenUpdating = False

Do While file <> ""

    Documents.Open Filename:=Path & file

    With ActiveDocument

        Set PcentCells = .Range(Start:=.Tables(2).Cell(6, 2).Range.Start, _
            End:=.Tables(2).Cell(6, 10).Range.End)
        PcentCells.Select

        With Selection.Find
            .Text = ","
            .Replacement.Text = "."
            .Forward = True
            .Wrap = wdFindContinue
            .Format = False
            .MatchCase = False
            .MatchWholeWord = False
            .MatchWildcards = False
            .MatchSoundsLike = False
            .MatchAllWordForms = False
            .Execute Replace:=wdReplaceAll '<-- replaces throughout document
            '.Execute Replace:=wdReplaceOne '<-- replaces in first cell but no other cells
        End With

    End With

    ActiveDocument.Save

    ActiveDocument.Close

    file = Dir()

Loop

Application.DisplayAlerts = True
Application.ScreenUpdating = True

End Sub

【问题讨论】:

标签: vba ms-word range


【解决方案1】:

根据您的问题描述,您的代码可以简化为:

Sub Replace_Percent_Separator()
'Correct percent separator in row 6, table 2
file = Dir("C:\xxx\Word\*.docx")

Do While file <> ""
  Documents.Open FileName:=Path & file, AddToRecentFiles:=False, Visible:=False
  With ActiveDocument
    With .Tables(2).Row(6).Range.Find
      .Text = ","
      .Replacement.Text = "."
      .Forward = True
      .Wrap = wdFindStop
      .Format = False
      .Execute Replace:=wdReplaceAll
    End With
    .Close SaveChanges:=True
  End With
  file = Dir()
Loop

End Sub

可以看出,无需选择任何内容,并且通过使用 wdFindStop 而不是 wdFindContinue,查找/替换将停止在应有的位置。

【讨论】:

  • 感谢Macropod! .Wrap = wdFindStop 是灵丹妙药,它节省了我在谷歌上搜索错误树的时间!还有更简洁的代码!非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多