在 Microsoft Word 中设置嵌套表格内的单元格格式

问题描述 投票:0回答:1

我一直在尝试理解Microsoft Word VBA代码。我很擅长 Excel VBA,但现在才看 Word 代码。我遇到的问题是表中有表。数据和表的数量将根据我当天的数据量而有所不同。

我需要考虑每个嵌套表格,并根据该单元格中的文本格式化特定单元格以进行颜色编码。例如,如果单元格数据是“Ea”,则将单元格着色为绿色背景,如果是“Pk”,则将其着色为黄色,等等。根据颜色,我可能还需要更改文本颜色,以便可以轻松阅读。在 Excel 中,条件格式是我的首选,但 Word 就没那么容易了。

我查看了代码中所示的更改表名称,看看这是否有帮助,但没有帮助。

使用我从这里的乐于助人的团队获得的一些代码,我能够让 Word 循环浏览每个嵌套表格。但在尝试了许多不同的代码之后,我无法让 if 语句起作用。调试错误“类型不匹配”消息不断出现在代码的“.Cell”部分。

我确信代码中缺少一些简单的东西。

Sub Test_4()

Dim mainTable As Word.Table
Dim nestedTable1 As Word.Table
Dim nestedTable2 As Word.Table
Dim n As Long
Dim ns As Long
Dim ns2 As Long
Dim NumOfTbl As Long
Dim C As Cell
Dim Table_Name As String


For Each mainTable In ActiveDocument.Tables
Table_Name = ""
n = n + 1
NumOfTbl = NumOfTbl + 1
'Debug.Print “——; Table; ” & n & ”; ——”

'nested level 1
ns = 0
For Each nestedTable1 In mainTable.Tables
nestedTable1.Select
ns = ns + 1
NumOfTbl = NumOfTbl + 1


MsgBox "Nested; Table; " & n & "." & ns
Table_Name = n & "." & ns
nestedTable1.Title = Table_Name

    If ActiveDocument.Bookmarks(Table_Name).Range.Tables(1).Cell(4, 4) = "Ea" Then
               ' Change Cell color to Green
               Else
                    ActiveDocument.Bookmarks(Table_Name).Range.Tables(1).Cell(4, 4) = "Pk"
                    'Change Cell color to Yellow
                
    End If

Table_Name = ""
Next nestedTable1
Next mainTable

`MsgBox "Total number of Lables: " & NumOfTbl - 1`

`End Sub`
vba ms-word
1个回答
0
投票

类型不匹配是因为您尝试将表格单元格

ActiveDocument.Bookmarks(Table_Name).Range.Tables(1).Cell(4, 4)
与字符串
"Ea"
进行比较,而这两个“类型”不具有可比性。

我猜你真正想要做的比较是表格单元格中的文本与字符串的比较

If ActiveDocument.Bookmarks(Table_Name).Range.Tables(1).Cell(4, 4).Range.Text = "Ea" Then

但是,这忽略了这样一个事实:每个表格单元格中的文本始终以“单元格结尾”字符(13 和 7)结尾,因此您想要使用的代码将删除这些字符,为此我们可以使用 VBA

 Replace
功能:

If Replace(ActiveDocument.Bookmarks(Table_Name).Range.Tables(1).Cell(4, 4).Range.Text, Chr$(13) & Chr$(7), vbNullString) = "Ea" Then

...这解决了第一个

.Cell
问题,您需要对后面一行的第二个问题进行同样的操作。

© www.soinside.com 2019 - 2024. All rights reserved.