在Microsoft Word上使用VBA替换表中多个单元格中的文本



我在Microsoft Word中有一个大表,我想突出显示最后一列中的单元格,并将其中的文本从";当前";至">已更改";。我知道你可以只使用复制粘贴或查找/替换,但我每天都会这样做多次,所以只突出显示并单击按钮会非常有用。

我在Excel中有一些VBA,它在电子表格中运行良好,但在Word中似乎不起作用。

Sub WordEdit()
Dim x As Range
For Each x In Selection
If x.Value <> "" Then x.Value = "Changed"
Next
End Sub

我不是VBA方面的专家,所以如果有任何帮助,我将不胜感激。谢谢

以下内容将更改单词"当前";至";"已更改";在选择中。请注意,对于此宏,必须将单词作为选择的一部分。它不需要在最后一列,也不需要在表中;它确实需要在选择中。

Sub ChangeSelectionCurrentToChanged()
' Charles Kenyon 13 Oct 2020
Dim rng As Range
'
Set rng = Selection.Range
With rng.Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = "Current"
.Replacement.Text = "Changed"
.Execute Replace:=wdReplaceAll
End With
Set rng = Nothing
End Sub

下面的宏将把单词";当前";至";"已更改";如果它位于文档中任何表的最后一列。选择什么并不重要。

Sub ChangeCurrentToChanged()
' Charles Kenyon 13 Oct 2020
Dim rng As Range
Dim iColumns As Long
Dim iRows As Long
Dim iCount As Long
Dim oTable As Table
'
For Each oTable In ActiveDocument.Tables
Let iColumns = oTable.Columns.Count
Let iRows = oTable.Rows.Count
For iCount = 1 To iRows
Set rng = oTable.Cell(iCount, iColumns).Range
With rng.Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = "Current"
.Replacement.Text = "Changed"
.Execute Replace:=wdReplaceAll
End With
Next iCount
Next oTable
Set oTable = Nothing
Set rng = nothing
End Sub

下面的宏将改变";当前";至";"已更改";在当前表(插入点所在的表(的最后一列中。

Sub ChangeCurrentToChangedSelectedTable()
' Charles Kenyon 13 Oct 2020
Dim rng As Range
Dim iColumns As Long
Dim iRows As Long
Dim iCount As Long
Dim oTable As Table
'
Set oTable = Selection.Tables(1)
Let iColumns = oTable.Columns.Count
Let iRows = oTable.Rows.Count
For iCount = 1 To iRows
Set rng = oTable.Cell(iCount, iColumns).Range
With rng.Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = "Current"
.Replacement.Text = "Changed"
.Execute Replace:=wdReplaceAll
End With
Next iCount
Set oTable = Nothing
Set rng = Nothing
End Sub

其中一个能满足你的需求吗?

最新更新