in reply to Re^2: Reading tables in MS Word
in thread Reading tables in MS Word

For general maintainability, I recommend avoiding $word->ActiveDocument. If you'll only be working with the current document, then do my $doc = $word->ActiveDocument somewhere at the top of your code.

Going from this Stackoverflow answer, you could use $doc->Selection->GoTo as suggested in the Microsoft documentation:

for my $para (1..$doc->Paragraphs->Count) { $doc->Selection->GoTo( What => wdGoToParagraph, Which => wdGoToAbs +olute, Count => $i ); my $para = $doc->Selection->Paragraphs->[0]; $doc->Selection->GoTo( What => wdGoToTable, Which => wdGoToNext ); my $table = $doc->Selection->Tables->[0]; ... }

This will still trip for paragraphs that have no table. Maybe in that case, it makes sense to step through all tables instead and then go backwards to find the corresponding paragraph or heading, depending on how your document is structured.

Replies are listed 'Best First'.
Re^4: Reading tables in MS Word
by spiral (Novice) on Jul 15, 2025 at 14:09 UTC
    It turns out all the info I need is in tables. I can do something like:
    my $tables = $word->ActiveDocument->{Tables}; for my $table (in $tables) { my $text = $table->ConvertToText(wdSeparateByTabs)->Text; ..... }
    The question is: instead of getting the content as a blob of text, can I get it per row and column?
        Never used VB, so I must be doing something wrong:
        for my $table (in $tables) { my $rownum=1;#VB starts at 1, not 0 while($rownum<=$table->Rows->Count){# the documentation #(rather sketchy) talks about Table.Column.Count #Probably the mistake is here my $cell1=$table->Cell($rownum,1); # get the cell of row $rownum and 1st column my $text1=$cell1->ConvertToText(wdSeparateByTabs)->Text; print "$text1\n"; $rownum++; } }