PDA

View Full Version : Basic VBA for removing rows/columns in word tables?



rhybeka
10-20-2021, 07:36 AM
Hi all,


I've got a piece of software that exports a translation document to a bunch of tables in a word document. I need to (from the screenshot)remove the first two tables, in the third table I need to remove the top row, then the first cell in the second row. In the final table I need to remove the first three columns. Then I'd need to loop the macro to run again for the next set of tables.

29071

I'm assuming this is all fairly simple if I just leverage the column or table headers. Is there an easy way to accomplish this? Thanks a bunch :)

gmayor
10-20-2021, 09:49 PM
What you request could be fairly simple. The problems however lie with your statement "Then I'd need to loop the macro to run again for the next set of tables." and the content of the last cell in table 3.
Do we assume that there are several blocks of four tables in the same document, each to be treated similarly?
If the following, which assumes there may be blocks of 4, but cannot identify the content of the cell in table 3, doesn't work for you, post a link to a sample document.


Sub Macro1()
'Graham Mayor - https://www.gmayor.com - Last updated - 21 Oct 2021
Dim oTable As Table
Dim i As Long, j As Long
If Not ActiveDocument.Tables.Count Mod 4 = 0 Then
MsgBox "The document has tables that are not in groups of 4", vbCritical
Exit Sub
End If
For i = ActiveDocument.Tables.Count To 1 Step -4
Set oTable = ActiveDocument.Tables(i)
For j = 3 To 1 Step -1
oTable.Columns(j).Delete
Next j
Set oTable = ActiveDocument.Tables(i - 1)
oTable.Rows(1).Delete
oTable.Columns(1).Delete
ActiveDocument.Tables(i - 3).Delete
ActiveDocument.Tables(i - 3).Delete
Next i
lbl_Exit:
Set oTable = Nothing
Exit Sub
End Sub

rhybeka
10-21-2021, 08:23 AM
Yes! My apologies, Graham! The document is an export of an exam, which has about 85 questions in it. Each question has this table layout. Which is why it would need to repeat. :) I'm sorry- I should have been more clear on that point. I'll give this a go and post a sample up which would help further, I'm sure!