我不熟悉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
答案 0 :(得分:0)
鉴于您的问题描述,您的代码可以简化为:
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,查找/替换将在应有的位置停止。