Do tables count in word count

Jeff wanted to know how to find out how many rows he had in a very long table in his Word document. Word Count doesn’t tell you — it tells you how many lines in the document, but each cell (except one) in a table is treated as a ‘line’ for Word Count purposes.

You can find out how many rows (and/or columns) there are in an individual table by checking the table properties. Here’s how:

  1. Select the entire table. This selects all rows and columns.
  2. Right-click on the selected table and select Table Properties from the shortcut menu.
  3. Click on the Row tab — the number of rows selected is listed at the top of the dialog box.
  4. Click on the Column tab — the number of columns selected is listed at the top of the dialog box.
  5. Click Cancel to close the Table Properties dialog box.

NOTE 1: If you now select another table to check its number of rows and columns, you may find that when the Table Dialog box opens to the last-viewed tab (Row or Columns), no numbers are displayed. Just go back to the Table tab, then click the Row or Column tab again and the number should display. If it doesn’t, save and close the document, then close Word. Reopen the document and try it again (see my comment dated 17 December 2022).

NOTE 2: Merged cells are mostly treated as though the rows and columns existed as they did when the table was first created. However, if you’ve merged all the cells from several adjacent rows, the row count will reduce.

/VBA Tips /How to Count Number of Rows in a Word Table?

Count Number of Rows in a Table

Microsoft Word does not have an automatic feature to count the number of rows in a table; however, you can create a simple macro to return these values

Method 1: Use the Information property to return the number of rows

Use the Microsoft Visual Basic for Applications Selection.Information property to return the number of rows in a table.

NOTE: The insertion point must be located in the table before you run the macro.

   Sub numRowsInCurrentTable()
      MsgBox Selection.Information(wdMaximumNumberOfRows)
   End sub

Method 2: Use the the Tables property to return the number of rows

Use the Microsoft Visual Basic for Applications Tables property to return the number of rows within a table. This method will return the total number of rows for the first table in the document. The insertion point does not need to be in the table.

   Sub numRowsInSpecificTable()
      MsgBox ActiveDocument.Tables(1).Rows.Count
   End Sub

Quick Steps

  • Open MS Word and Select any table
  • Press Alt+F11, Copy Paste the code in this Article
  • Press F5.

Related

  • Remove From My Forums
  • Question

  • 0 down vote favorite

    I am using Interop to add tables to a Word document, but am having trouble getting a count of the tables in the document.

    I want to work with the latest table that has been pasted into the document, so I am trying to reference it like this:

    oWordDoc.Tables[iTable].Cell(2, 1).Range.Text = sValues[1];

    but I am getting an error ‘The requested member of the collection does not exist.

    in trying to track down that I want to see what the count of tables is, so I tried 

    ?oWordDoc.Tables.Count

    in the Immediate Window and am getting the below error

    ‘System.Linq.ParallelEnumerable.Count(System.Linq.ParallelQuery, System.Func)’ is a ‘method’, which is not valid in the given context

    how should I reference the Tables collection in Word using Interop to get the count?

Answers

  • Hello,

    You can’t just call a ctor of the Document class. Instead, you need to create a new one using the Word Object Model (see the

    Documents.Add method) or get the active one using the ActiveDocument property of the Application class.

    • Marked as answer by

      Tuesday, December 31, 2013 1:41 AM

  • Hi «Bananas»

    Thank you for the code — I think we’ve found the problem.

    The only object for which you should use the New keyword with Word is Word.Application.

    You should NOT use New for Documents. Word won’t show an error, but your code can’t work correctly with the document generated in this way.

    Instead, use oWord.Documents.Add(//parameters here);


    Cindy Meister, VSTO/Word MVP,
    my blog

    • Marked as answer by
      Luna Zhang — MSFT
      Tuesday, December 31, 2013 1:41 AM

  1. Dec 11th, 2008, 08:42 PM


    #1

    John1in2 is offline

    Thread Starter


    Member


    Resolved [RESOLVED] Word: How to count number of tables in Word Document?

    I am opening tables from Word and extracting data. The only trouble I am having is that I do not have the same number of tables every time I run the program.

    How do I detect the number of tables that are in the document that I just opened?

    I did a search and found this-
    http://www.vbforums.com/showthread.p…=detect+tables

    which led me to this code (Tables is supposed to be 2 but when I run it its only 1).

    Dim T as Table
    Dim i as Integer
    Dim Tables as Integer

    For Each T In wdDoc.Tables
    i = i + 1
    Exit For
    Next
    Tables = i


  2. Dec 11th, 2008, 08:46 PM


    #2

    John1in2 is offline

    Thread Starter


    Member


    Re: Word: How to count number of tables in Word Document?

    OK, this works but I don’t know why-

    For Each T In wdDoc.Tables
    i = i + 1
    Next
    Tables = i

    I deleted the «end for». What does that do?


  3. Dec 11th, 2008, 08:48 PM


    #3

    Re: Word: How to count number of tables in Word Document?

    It spits you right out of the For loop, so you would have only counted 1 table each time. An easier way to get the tables would be to use wdDoc.Tables.Count.

    Code:

    Tables = wdDoc.Tables.Count


  4. Dec 11th, 2008, 11:37 PM


    #4

    John1in2 is offline

    Thread Starter


    Member


    Re: Word: How to count number of tables in Word Document?

    Thanks, I knew there was something like that aviable to me, but I cannot find the list of functions/attributes, etc… Not like the old days when you just had 1 manual.

    Is there a reference guide for Excel and Word that lists everything? Or just the MSft website?


  5. Dec 12th, 2008, 08:15 AM


    #5

    Re: [RESOLVED] Word: How to count number of tables in Word Document?

    You have Intellisense and the Word VBA manual. It’s better than you think. From the VB editor: Help->Contents, Help Pane->Microsoft Word Visual Basic Reference->Microsoft Word Object Model.

    You also have the object browser (F2).


  6. Dec 12th, 2008, 11:01 AM


    #6

    John1in2 is offline

    Thread Starter


    Member


    Re: [RESOLVED] Word: How to count number of tables in Word Document?

    Ok, thank you. I’ll skim through those.


  7. Apr 18th, 2014, 11:08 PM


    #7

    francisco_villa is offline


    New Member


    Re: [RESOLVED] Word: How to count number of tables in Word Document?

    Dear friends….

    i want to count the tables but between pages… for example how many tables are between page 1 and page 3?… how can i do it with VBA Word?….

    thanks for your answers…


25 / 25 / 0

Регистрация: 10.03.2010

Сообщений: 206

1

Word

27.02.2020, 09:37. Показов 1453. Ответов 19


Студворк — интернет-сервис помощи студентам

Доброго времени суток! Я в VBA новичок (пишу изредка, по надобности), так вот столкнулся с документом docx (использую word 2016, VBA 7.1), в котором нужно прочекать все таблицы документа на наличие в них определенных записей, с дальнейшим их удалением, а ActiveDocument.Tables.count возвращает значение гораздо меньшее, нежели их (таблиц) действительное количество. Тобишь For Each curTable In ActiveDocument.Tables отрабатывает не верно, в чём может быть проблема?



0



4131 / 2235 / 940

Регистрация: 01.12.2010

Сообщений: 4,624

27.02.2020, 10:22

2

Значит таблицы вложенные.

Миниатюры

ActiveDocument.Tables.count видит не все таблицы
 



1



25 / 25 / 0

Регистрация: 10.03.2010

Сообщений: 206

27.02.2020, 12:00

 [ТС]

3

Цитата
Сообщение от pashulka
Посмотреть сообщение

Значит таблицы вложенные.

Нет, таблицы идут друг за другом!



0



4131 / 2235 / 940

Регистрация: 01.12.2010

Сообщений: 4,624

27.02.2020, 12:08

4

Тогда продолжаем гадать на кофейной гуще, авось найдутся телепаты и увидят Ваш файл



1



25 / 25 / 0

Регистрация: 10.03.2010

Сообщений: 206

27.02.2020, 12:29

 [ТС]

5

Цитата
Сообщение от pashulka
Посмотреть сообщение

Тогда продолжаем гадать на кофейной гуще, авось найдутся телепаты и увидят Ваш файл

Файл, к сожалению, выложить не могу, информация конфиденциальная. могу сказать, что конвертировался файл из pdf через Adobe Reader Pro.



0



Модератор

Эксперт MS Access

11336 / 4655 / 748

Регистрация: 07.08.2010

Сообщений: 13,484

Записей в блоге: 4

27.02.2020, 12:35

6

Цитата
Сообщение от eXtream
Посмотреть сообщение

информация конфиденциальная. могу сказать

делов то на 5 мин
— сделайте копию файла
— замените все буквы/цифры на ~

нужен ведь каркас документа, а не информация



1



25 / 25 / 0

Регистрация: 10.03.2010

Сообщений: 206

27.02.2020, 12:55

 [ТС]

7

Цитата
Сообщение от shanemac51
Посмотреть сообщение

нужен ведь каркас документа, а не информация

Ну да, чёт тупанул.



0



25 / 25 / 0

Регистрация: 10.03.2010

Сообщений: 206

27.02.2020, 15:06

 [ТС]

8

Проанализировал я структуру и заметил что некоторые таблицы находятся внутри каких-то других объектов, теперь вопрос №2, как получить к ним доступ?



0



Модератор

Эксперт MS Access

11336 / 4655 / 748

Регистрация: 07.08.2010

Сообщений: 13,484

Записей в блоге: 4

27.02.2020, 15:15

9

Цитата
Сообщение от eXtream
Посмотреть сообщение

внутри каких-то других объектов,

это могут быть
— рамки
— надписи
— коллонтитулы

документ еще не смотрела



1



Модератор

Эксперт MS Access

11336 / 4655 / 748

Регистрация: 07.08.2010

Сообщений: 13,484

Записей в блоге: 4

27.02.2020, 16:30

10

у вас, согласно перебору объектов
13 таблиц
19 автофигур, это могут быть и рисунки и символы и таблицы и таблицы, смоделированные линиями
1 надпись — тоже может быть все

я не случайно просила заменить символы на ~.чтобы было видно, где есть текст
простое удаление текста — не показывает, где был текст

Миниатюры

ActiveDocument.Tables.count видит не все таблицы
 



2



25 / 25 / 0

Регистрация: 10.03.2010

Сообщений: 206

27.02.2020, 16:36

 [ТС]

11

Проанализировал я структуру и заметил что некоторые таблицы находятся внутри каких-то других объектов, теперь вопрос №2, как получить к ним доступ?

Цитата
Сообщение от shanemac51
Посмотреть сообщение

у вас, согласно перебору объектов
13 таблиц
19 автофигур, это могут быть и рисунки и символы и таблицы и таблицы, смоделированные линиями
1 надпись — тоже может быть все

Если эти объекты являются контейнерами для таблиц, то можно каким-то образом получить к ним (таблицам) доступ?



0



Модератор

Эксперт MS Access

11336 / 4655 / 748

Регистрация: 07.08.2010

Сообщений: 13,484

Записей в блоге: 4

27.02.2020, 16:44

12

Цитата
Сообщение от shanemac51
Посмотреть сообщение

я не случайно просила заменить символы на ~.чтобы было видно, где есть текст

сделайте это ЗАМЕНОЙ НА КОПИИ ДОКУМЕНТА
[А-Яа-яA-Za-z0-9] на ~
мне будет более наглядно

Миниатюры

ActiveDocument.Tables.count видит не все таблицы
 



1



25 / 25 / 0

Регистрация: 10.03.2010

Сообщений: 206

27.02.2020, 16:59

 [ТС]

13

Вот дополненный файл: чистый_1.zip



0



Модератор

Эксперт MS Access

11336 / 4655 / 748

Регистрация: 07.08.2010

Сообщений: 13,484

Записей в блоге: 4

27.02.2020, 18:24

14

в этом 9 чистых таблиц и 19 таблиц в автофигурах(некоторые -это только шапки, другие с данными)
умеете ли вы работать с макросами, т.е.
-записать в normal.dot
-вызвать на выполнение

пока — это каркас вашего документа в НТМ



1



25 / 25 / 0

Регистрация: 10.03.2010

Сообщений: 206

27.02.2020, 19:24

 [ТС]

15

Спасибо за проделанную работу, но сверхзадача в том, что данный документ не единственный (т.е. будут новые, с уже другой структурой), и я хочу написать скрипт который будет пробегать все таблицы, как самостоятельные, так и содержащиеся в каких-либо других объектах и выполнять удаление определенных записей.

И в связи с этим встаёт задача:
— получить список всех объектов, которые могут быть контейнерами для других объектов,
— проверить есть ли в них таблица
— далее поиск по таблице с удалением ячеек строки со сдвигом вверх!

Я не прошу вас писать мне скрипт, мне нужно понять как получить список всех объектов и проверить есть ли в них таблица!



0



Модератор

Эксперт MS Access

11336 / 4655 / 748

Регистрация: 07.08.2010

Сообщений: 13,484

Записей в блоге: 4

27.02.2020, 19:30

16

Цитата
Сообщение от eXtream
Посмотреть сообщение

хочу написать скрипт который будет пробегать все таблицы

я про это вас и спрашиваю
упрошенный я написала, но реальный будет конечно сложнее, т.к. помимо таблиц есть еще и гладкий текст



1



25 / 25 / 0

Регистрация: 10.03.2010

Сообщений: 206

27.02.2020, 19:39

 [ТС]

17

Цитата
Сообщение от shanemac51
Посмотреть сообщение

я про это вас и спрашиваю
упрошенный я написала, но реальный будет конечно сложнее, т.к. помимо таблиц есть еще и гладкий текст

Я понимаю. Буду решать проблемы по мере их поступления. Сейчас мне нужно знать как в VBA получить список всех объектов и проверить есть ли в них таблица.



0



shanemac51

Модератор

Эксперт MS Access

11336 / 4655 / 748

Регистрация: 07.08.2010

Сообщений: 13,484

Записей в блоге: 4

27.02.2020, 20:02

18

у word.activedocument есть коллекции
— shapes
— inlineshapes
— frames

и циклы типа

dim sh as shape
for each sh in word.activedocument.shapes
»»’ здесь обработка
next sh

Добавлено через 24 секунды
у word.activedocument есть коллекции
— shapes
— inlineshapes
— frames

и циклы типа

Visual Basic
1
2
3
4
dim sh as shape
for each sh in word.activedocument.shapes 
'''''  здесь обработка
next sh



1



25 / 25 / 0

Регистрация: 10.03.2010

Сообщений: 206

27.02.2020, 20:11

 [ТС]

19

Цитата
Сообщение от shanemac51
Посмотреть сообщение

у word.activedocument есть коллекции
— shapes
— inlineshapes
— frames

Да, я эти коллекции я в справочнике видел, а как определить есть ли в объектах этих коллекций таблица, чего-то ни в свойствах ни в методах я не могу ни чего найти подходящего по смыслу.



0



shanemac51

Модератор

Эксперт MS Access

11336 / 4655 / 748

Регистрация: 07.08.2010

Сообщений: 13,484

Записей в блоге: 4

27.02.2020, 20:23

20

eXtream,
например

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
Sub m71shape()
Dim sh As Shape
Debug.Print Word.ActiveDocument.Shapes.Count
 
For Each sh In Word.ActiveDocument.Shapes
'Debug.Print
 sh.Select
 If Selection.Tables.Count > 0 Then
Debug.Print sh.Name; " таблица есть"
End If
Next sh
End Sub



1



IT_Exp

Эксперт

87844 / 49110 / 22898

Регистрация: 17.06.2006

Сообщений: 92,604

27.02.2020, 20:23

Помогаю со студенческими работами здесь

Нюансы синтаксиса: statement for — как понимать запись for (count=0, mask=1; count != 16; count++, mask<<= 1)?
Много всяких языков попадалось, относительно много конечно, но такое вижу первый раз, что бы тело…

Gembox.Spreadsheet и Excel (2007+) TABLES («умные таблицы»)
Здравствуйте!
Кто-нибудь в курсе, умеет ли Gembox.Spreadsheet обращаться к &quot;умным таблицам&quot;…

Перезагрузить mysql сервер с обнулением таблицы mysql — опция mysqld —skip-grant-tables
Здравствуйте , столкнулся с такой проблемой ,неудаётся подключиться к серверу mysql из командной…

Выборка из таблицы по условию + COUNT
Здравствуйте! Помогите пожалуйста!
Есть таблица, содержащая дату, логин пользователя, признак…

Искать еще темы с ответами

Или воспользуйтесь поиском по форуму:

20

Понравилась статья? Поделить с друзьями:
  • Dividing cells in word
  • Do some word searches
  • Dividing cell in excel
  • Dividing a word into morphemes
  • Do pdf converter convert from pdf to word