May 16 2022 06:22 AM
Hi,
I'm supplied Word documents that contain a table that has differing valid rows therefore I need a variable to count the valid rows.
In Excel this would be something like:
Sub Test() With ActiveSheet lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row MsgBox lastRow End With End Sub
I can use the following within word vba to count rows excluding the header row but I don't appear to be able to get .End(xlUP)
Dim row As Integer
Dim excelApp As Object
Set excelApp = CreateObject("Excel.Application")
row = excelApp.Worksheetfunction.Clean(ActiveDocument.Tables(1).UsedRange.Rows.Count
Any ideas how I can count valid rows?
TIA
May 17 2022 02:23 AM
Use
Dim objSS As InlineShape
With ActiveDocument.InlineShapes(1)
.OLEFormat.DoVerb wdOLEVerbHide
With .OLEFormat.Object.Application
With .workbooks(1).Worksheets(1)
MsgBox .Range("A1").currentregion.Rows.Count
End With
End With
End With
May 17 2022 02:53 AM
May 17 2022 04:26 AM
@a_bonsey Is a line of the code highlighted when it fails?
This is the result of running the code here
May 17 2022 06:21 AM
May 17 2022 01:48 PM
Sure. Here you go
May 17 2022 03:23 PM
@a_bonsey That document contains a Word table, not an Excel worksheet.
The following macro will tell you how many rows contain data:
With ActiveDocument.Tables(1)
For i = 1 To .Rows.Count
If Len(.Cell(i, 1).Range) < 3 Then
Exit For
End If
Next i
End With
MsgBox "The table contains data in " & i - 1 & " rows, including the header row."
May 18 2022 01:36 AM
That worked brilliantly and looked so obvious when you laid it out like that.
Just couldn't see the woods for the trees as they say!!
Thanks again
May 18 2022 02:25 AM - edited May 18 2022 02:27 AM
Hi,
I tried tweaking the vba slightly to see what a debug/msgbox would should for the cell(i,1). In the debug (and Msgbox) I get a 'rectangular box' appearing (see attached image).
Are you able to tell me what causes this to appear?
May 18 2022 02:40 AM
@a_bonsey The range of an empty cell in a Word table has a length of 2. Therefore, the code checks to see if the length of the range of each cell is < 3. If it is, then the row is not valid according to your nomenclature.
In the Immediate Window, you should enter
MsgBox Len(Selection.Cells(1).Range)
when the selection is in a cell.