在开发宏以查看word文档和更改表中的背景颜色列时,我遇到了困难。
宏需要查看word文档中的每个表,如果单元格具有文本“PH”,则该单元格的列需要更改背景颜色。
我已经有一段时间没用VB了。我在下面也尝试过cell.range和Selection.Find,但是一直都有错误。
Private Sub Document_Open()
Dim Tbl As Table
Dim Cel As Cell
Dim Rw As Row
Dim Col As Columns
For Each Tbl In ActiveDocument.Tables
Set Col = Tbl.Columns
For Each c In Col
With Selection.Find
.Execute FindText:="Public Holiday"
c.Shading.BackgroundPatternColorIndex = wdRed
End With
Next
Next
End Sub
发布于 2019-08-05 21:03:29
测试
Dim Tbl As Table
Dim i As Integer, j As Integer
For Each Tbl In ActiveDocument.Tables
For j = 1 To Tbl.Columns.Count
For i = 1 To Tbl.Rows.Count
If InStr(1, Tbl.Cell(i, j).Range.Text, "PH") Then Tbl.Columns(j).Shading.BackgroundPatternColor = -738132122
Next
Next
Next
循环遍历每个单元格并检查它是否包含"PH"
,如果是,则对该列进行着色。
发布于 2019-08-06 03:42:28
下面的方法对我有用,比循环表格和表格单元格要快一些。
相反,它在整个文档中搜索PH
,然后检查找到的区域是否在表中。如果是,则对该列进行格式化。然后,搜索从下一个单元格开始。请注意,我已经将此代码设置为“匹配大小写”,以便它只获取PH值,而不是ph值或任何其他变量。否则,它最终会识别诸如电话之类的单词.
处理表列通常很棘手,因为表列看起来可能是连续的,但它不是。只有行是连续的(单词解析从左到右,从上到下)。因此,除非一个接一个地选择列,否则就不可能逐列搜索。这是问题中的代码的另一个问题:它使用Selection
,但所选内容不会更改为应该搜索的内容。
Private Sub Document_Open()
Dim rngFind As Word.Range
Dim found As Boolean
Set rngFind = ActiveDocument.content
With rngFind.Find
.ClearFormatting
.Wrap = wdFindStop
.Text = "PH"
.MatchCase = True
found = .Execute
Do
If found Then
If rngFind.Information(wdWithInTable) Then
rngFind.Columns(1).Shading.BackgroundPatternColorIndex = wdRed
rngFind.MoveStart wdCell, 1
Else
rngFind.Collapse wdCollapseEnd
End If
End If
found = .Execute
Loop While found
End With
End Sub
https://stackoverflow.com/questions/57369075
复制