I have been trying to understand Microsoft word VBA code. I am pretty good at Excel VBA but just now looking at Word code. The issue I have is I have tables within tables. The data and the number of tables will vary depending on how much data I have for that day.
I need to go thought each nested table and format a particular cell to be color coded based on the text in that cell. For example, if the cell data is “Ea” then color the cell with a green background, if it is “Pk” then color it yellow, ect. Depending on the color I may have to also change the text color so it can be easily read. In Excel conditional formatting would be my go-to option but Word is not that easy.
I looked at changing the table name as seen in the code, to see if that would help but it did not.
Using some of the code I got from the helpful team here I was able to get Word to cycle through each nested table. But after trying many different codes I cannot get the if statement to work. the debug error “type mismatch” message keeps coming up at the “.Cell” portion of the code.
I am sure there is something simple that I am missing in the code.
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
Fafoworks is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.