vba - 如何更改特定相邻列的表格中的文本?
问题描述
我正在为 WORD 使用 VBA 宏,以便用“”替换所有“[”字符。该宏可以很好地用某种颜色替换所有表中的所有字符。
如何添加 if 语句以使其仅在 A 列包含“测试”时才起作用
前:
标题 1 | [文本 |
---|---|
测试: | [文本 |
后:
标题 1 | [文本 |
---|---|
测试: | 文本 |
到目前为止,我得到了这个并且它工作正常(但对于所有表行而不是特定于“测试”行。
Sub FindChar2()
Dim oTbl As Table
Dim stT As Long, enT As Long
Dim stS As Long, enS As Long
With Selection.Find ' Replacement
.Text = "["
.Replacement.Text = ""
.Forward = True
.Wrap = wdFindContinue
End With
For Each oTbl In ActiveDocument.Tables
If oTbl.Shading.BackgroundPatternColor = RGB(176, 255, 137) Then
oTbl.Columns(1).Select
Do While Selection.Find.Execute
stT = oTbl.Range.Start ' table range
enT = oTbl.Range.End
stS = Selection.Range.Start ' found text range
enS = Selection.Range.End
If stS < stT Or enS > enT Then Exit Do
Selection.Collapse wdCollapseStart
Selection.Find.Execute Replace:=wdReplaceOne
Loop
Selection.Collapse wdCollapseEnd
End If
Next
End Sub
解决方案
假设“测试”是 A 列中的唯一内容(我注意到您的样本有“测试:),您可以使用:
Sub TblFnd()
Application.ScreenUpdating = False
Dim Tbl As Table, Rng As Range
For Each Tbl In ActiveDocument.Tables
With Tbl
If .Shading.BackgroundPatternColor = RGB(176, 255, 137) Then
Set Rng = .Range
With .Range
With .Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = "["
.Forward = True
.Wrap = wdFindStop
.Format = False
End With
Do While .Find.Execute
If .InRange(Rng) Then
If .Cells(1).ColumnIndex = 2 Then
If Split(.Cells(1).Row.Cells(1).Range.Text, vbCr)(0) = "Test" Then .Text = ""
End If
Else
Exit Do
End If
.Collapse wdCollapseEnd
Loop
End With
End If
End With
Next
Application.ScreenUpdating = True
End Sub
推荐阅读
- xamarin - 如何使用 MessagingCenter 将 ToggledEventArgs 发送给订阅者?
- php - Sweetalart 不在同一页面上发布 ajax 请求
- python - 根据python中的文件名向数据框添加列
- sql - 选择总计和如果读取
- jqgrid - jqgrid设置的scrollLeftOffset是什么意思?
- .htaccess - 在 htaccess 中强制使用 HTTPS,同时仅使公用文件夹可访问
- javascript - Javascript Dsiplay 2 个字符串在一个警报中
- excel - 如何在运行 VBA 的情况下更新 API 库存值
- java - 如何识别导致代码失败的边缘案例?
- php - 如何在注册过程中检查用户是否输入了字母数字