strajano
strajano

Reputation: 69

Word VBA: Get table that is on the display screen at the moment

Suppose you have a microsoft word file (.DOCX), you open it and start to view it, using the mouse scrolling, from page 1 towards the last page.

Then, suppose you see a table, for instance, on page 4.

Now I ask: is it possible for Word-VBA to say to you what is the index or name of that table that is on the screen at the moment, no matter where is cursor located?

I want word-VBA fullfil a table that I am seeing at that moment, no matter where the cursor is located.

I hope I was clear enough...

Upvotes: 0

Views: 169

Answers (1)

Cindy Meister
Cindy Meister

Reputation: 25663

Word doesn't have a direct way to get what's visible on-screen. It can be calculated, sort of, but not with 100% accuracy.

The following code sample does the trick for me, on my machine. It may need some tweaking to work on a different set up.

The object model does return the co-ordinates of the application window (ActiveWindow, here), the height of that Window and the UsableHeight - the height of the actual document working space. That can be used to get an estimated position.

There's also a Windows API function equivalent - RangeFromPoint - for a Window object that returns the a Range in the document for the given screen co-ordinates.

This code calculates a left and top position for the start of the visible part of the document, as well as for the end of the visible document. (In my test, it was a bit more, but not much). It then checks whether there is one or more tables within that scope. If it is, it takes the first one ( Set tbl = rngTargetStart.Tables(1)) - this returns the object your code needs to work with. As a "bonus", the code prints the index number of the table in the document and the page it's on to the Immediate Window.

Sub CheckForTableOnPage()
    Dim WordWindowTop As Long   'in points
    Dim WordWindowLeft As Long  'in points
    Dim windowUsableHeight As Long 'in points
    Dim rngTargetStart As Range
    Dim rngTargetEnd As Range
    Dim pageNumberTarget As Long
    Dim tbl As Table

    WordWindowTop = ActiveWindow.height
    WordWindowLeft = ActiveWindow.left
    windowUsableHeight = ActiveWindow.UsableHeight
    RibbonFactor = 200
    Set rngTargetStart = ActiveWindow.RangeFromPoint(WordWindowLeft, WordWindowTop - windowUsableHeight)
    Set rngTargetEnd = ActiveWindow.RangeFromPoint(WordWindowLeft, WordWindowTop + windowUsableHeight)
    rngTargetStart.End = rngTargetEnd.End
    If rngTargetStart.Tables.Count >= 1 Then
        pageNumberTarget = rngTargetStart.Information(wdActiveEndPageNumber)
        Set tbl = rngTargetStart.Tables(1)
        rngTargetStart.Start = ActiveDocument.Content.Start
        Debug.Print "The table on page " & pageNumberTarget & " is number: " & rngTargetStart.Tables.Count
    End If
End Sub

Upvotes: 1

Related Questions