View Single Post
 
Old 12-17-2022, 12:35 PM
karkey karkey is offline Windows 10 Office 2013
Novice
 
Join Date: Jan 2021
Posts: 19
karkey is on a distinguished road
Default insertbefore in all cells and columns

Code:
Sub InsertTableTags()

Dim tbl As Table
Dim rng As Range
Dim row As row

' Loop through all tables in the document
For Each tbl In ActiveDocument.Tables
    Set rng = tbl.Range

    ' Check if all columns are merged
    If tbl.Rows(2).Cells.Count > 1 Then
        ' Insert <TC> in first row
        rng.Cells(1).Range.InsertBefore Text:="<TC>"
        
    End If

    ' Loop through rows in the table
    For Each row In tbl.Rows
        Set rng = row.Range

        ' Check if current row is the second row
        If row.Index = 2 Then
            ' Check if all columns are merged
            If tbl.Rows(2).Cells.Count > 1 Then
                ' Insert <TCH> in second row
                rng.Cells(1).Range.InsertBefore Text:="<TCH>"
            End If
        ' Check if current row is not the first or last row
        ElseIf row.Index > 2 And row.Index < tbl.Rows.Count Then
            ' Insert <TT> in all cells
            rng.Cells(1).Range.InsertBefore Text:="<TT>"
        ' Check if current row is the last row
        ElseIf row.Index = tbl.Rows.Count Then
            ' Check if all columns are merged
            If tbl.Rows(tbl.Rows.Count).Cells.Count > 1 Then
                ' Insert <TTL> in last row
                rng.Cells(1).Range.InsertBefore Text:="<TTL>"
            End If

            ' Check if "Source", "Notes", or "Note" is found in the last row
            If InStr(rng.Text, "Source") > 0 Or InStr(rng.Text, "Notes") > 0 Or InStr(rng.Text, "Note") > 0 Then
                ' Insert <TTS> in all cells of the last row
                rng.Cells(1).Range.InsertBefore Text:="<TTS>"
            End If
        End If
    Next row
Next tbl

End Sub
while run the above code it insertBefore only in 1st column need to insert in all columns
Attached Files
File Type: docx TableTagTesting.docx (12.1 KB, 4 views)
Reply With Quote