Посчитать заполненные ячейки в excel vba

 

ALFA

Пользователь

Сообщений: 243
Регистрация: 13.09.2013

Подскажите, как, открыв макросом стороннюю книгу, можно на определенном ее листе посчитать кол-во заполненных ячеек в столбце A.

 

hk1209

Пользователь

Сообщений: 271
Регистрация: 01.01.1970

 

ALFA

Пользователь

Сообщений: 243
Регистрация: 13.09.2013

Set wb2 = Workbooks.Open(«C:UsersU_M06TTDesktopExcelКачествоМарт 2014.xls», 0, 1)   ‘открыл книгу
Далее необходимо посчитать кол-во заполненных ячеек в файле Март 2014.xls   sheets(«данные»).range(«A:A»)

Скажите что еще написать, я в этом не оч силен.

 

ALFA

Пользователь

Сообщений: 243
Регистрация: 13.09.2013

#4

15.05.2014 20:31:10

Нашел решение, всем спасибо!

Код
ThisWorkbook.Worksheets("данные".Activate 
ActiveSheet.Cells.SpecialCells(xlCellTypeLastCell).Activate 
k = ActiveCell.Row    'номер последней заполненной строки
 

Scripter

Пользователь

Сообщений: 255
Регистрация: 06.02.2014

#5

16.05.2014 01:48:48

так кол-во заполненных

Код
Msgbox "Кол-во заполненных ячеек в столбце А: " & Worksheetfunction.CountA(Columns(1)) 

так номер последней строки

Код
Msgbox "Номер последней заполненной строки: " & Cells(Rows.Count,1).end(xlup).row 

Изменено: Scripter16.05.2014 08:58:46

 

ALFA

Пользователь

Сообщений: 243
Регистрация: 13.09.2013

А если необходимо открыв книгу, посчитать Кол-во заполненных ячеек, предварительно выбрав лист, как использовать Worksheetfunction.CountA(Columns(1))

 

Scripter

Пользователь

Сообщений: 255
Регистрация: 06.02.2014

#7

16.05.2014 17:44:27

Если нужно чтоб при открытии книги срабатывал код, то нужно поместить код в «Эта книга»

Если вам нужно посчитать ВСЕ заполненные (не найти последнюю строку) ячейки на листе:

Скрытый текст

В определенном столбце

Скрытый текст

или

Скрытый текст

Найти последнюю строку на листе, если последнее значение которое увеличивает диапазон может быть в любом столбце

Скрытый текст

Найти последнюю строку на листе по определенному полю

Скрытый текст

Изменено: Scripter16.05.2014 17:48:46

My first column is an index, with monotonously increasing numbers, which ends at a non predictable point.
Now I want to find out, how many entries this column has. Is there a better way than iterating throug this and watch out for an empty cell?

eli-k's user avatar

eli-k

10.7k11 gold badges43 silver badges44 bronze badges

asked Jul 14, 2010 at 9:27

poeschlorn's user avatar

If you want to find the last populated cell in a particular column, the best method is:

Range("A" & Rows.Count).End(xlUp).Row

This code uses the very last cell in the entire column (65536 for Excel 2003, 1048576 in later versions), and then find the first populated cell above it. This has the ability to ignore «breaks» in your data and find the true last row.

praegustator's user avatar

answered Oct 6, 2011 at 21:48

MrKowz's user avatar

MrKowzMrKowz

2713 silver badges3 bronze badges

1

One way is to: (Assumes index column begins at A1)

MsgBox Range("A1").End(xlDown).Row

Which is looking for the 1st unoccupied cell downwards from A1 and showing you its ordinal row number.

You can select the next empty cell with:

Range("A1").End(xlDown).Offset(1, 0).Select

If you need the end of a dataset (including blanks), try: Range(«A:A»).SpecialCells(xlLastCell).Row

Community's user avatar

answered Jul 14, 2010 at 10:03

Alex K.'s user avatar

Alex K.Alex K.

170k30 gold badges263 silver badges286 bronze badges

2

You can also use

Cells.CurrentRegion

to give you a range representing the bounds of your data on the current active sheet

Msdn says on the topic

Returns a Range object that represents
the current region. The current region
is a range bounded by any combination
of blank rows and blank columns.
Read-only.

Then you can determine the column count via

Cells.CurrentRegion.Columns.Count

and the row count via

Cells.CurrentRegion.Rows.Count

answered Jul 14, 2010 at 10:18

almog.ori's user avatar

almog.orialmog.ori

7,8291 gold badge35 silver badges49 bronze badges

1

You may also use:

UsedRange.Rows.Count

answered Jul 2, 2011 at 5:38

AMIB's user avatar

AMIBAMIB

3,1823 gold badges19 silver badges19 bronze badges

0

To find the last filled column use the following :

lastColumn = ActiveSheet.Cells(1, Columns.Count).End(xlToLeft).Column

Hugo Dozois's user avatar

Hugo Dozois

8,05712 gold badges53 silver badges58 bronze badges

answered Mar 6, 2013 at 18:13

deva ruban's user avatar

Подсчет количества ячеек в диапазоне в зависимости от их содержимого методами Count, CountA и CountBlank объекта WorksheetFunction из кода VBA Excel.

Метод WorksheetFunction.Count

Определение

Определение метода Count объекта WorksheetFunction в VBA Excel:

Метод WorksheetFunction.Count подсчитывает в заданном диапазоне (массиве) количество ячеек (элементов массива), содержащих числа, и возвращает значение типа Double.

Синтаксис

Синтаксис метода Count объекта WorksheetFunction:

WorksheetFunction.Count(Arg1, Arg2, ..., Arg30)

Параметры

Параметры метода Count объекта WorksheetFunction:

Параметр Описание
Arg1-Arg30 От 1 до 30 аргументов, которые могут содержать различные типы данных или ссылаться на них.

Примечания

  • Метод WorksheetFunction.Count позволяет получить количество числовых значений в диапазоне ячеек или в массиве.
  • При подсчете учитываются аргументы, которые являются числами, датами или текстовым представлением чисел.
  • Логические значения учитываются при подсчете только в том случае, если они введены непосредственно в список аргументов.

Метод WorksheetFunction.CountA

Определение

Определение метода CountA объекта WorksheetFunction в VBA Excel:

WorksheetFunction.CountA — это метод, который подсчитывает в заданном диапазоне количество непустых ячеек, и возвращает значение типа Double.

Синтаксис

Синтаксис метода CountA объекта WorksheetFunction:

WorksheetFunction.CountA(Arg1, Arg2, ..., Arg30)

Параметры

Параметры метода CountA объекта WorksheetFunction:

Параметр Описание
Arg1-Arg30 От 1 до 30 аргументов, которые могут содержать различные типы данных или ссылаться на них.

Примечания

  • Метод WorksheetFunction.CountA позволяет получить количество непустых ячеек в заданном диапазоне.
  • Непустыми являются ячейки, которые содержат любые данные, включая значения ошибок и пустые строки ("").
  • Тесты показывают, что метод WorksheetFunction.CountA в массиве, созданном путем присвоения ему значений диапазона, содержащего пустые ячейки, все равно считает все элементы массива, как содержащие значения.

Метод WorksheetFunction.CountBlank

Определение

Определение метода CountBlank объекта WorksheetFunction в VBA Excel:

WorksheetFunction.CountBlank — это метод, который подсчитывает в заданном диапазоне количество пустых ячеек, и возвращает значение типа Double.

Синтаксис

Синтаксис метода CountBlank объекта WorksheetFunction:

WorksheetFunction.CountBlank(Arg1)

Параметры

Параметры метода CountBlank объекта WorksheetFunction:

Параметр Описание
Arg1 Диапазон, в котором необходимо подсчитать количество пустых ячеек.

Примечания

  • Метод WorksheetFunction.CountBlank позволяет получить количество пустых ячеек в заданном диапазоне.
  • Пустыми являются ячейки, которые не содержат никаких данных.
  • Также подсчитываются, как пустые, ячейки с формулами, которые возвращают пустые строки ("").
  • Ячейки с нулевыми значениями в подсчете не участвуют.

Примеры

Таблица для строк кода VBA Excel со ссылками на диапазон "A1:C5", а также с массивом его значений в качестве аргументов:

Примеры с WorksheetFunction.Count

Sub Primer1()

Dim n As Double, a() As Variant

    n = WorksheetFunction.Count(Range(«A1:C5»))

MsgBox n  ‘Результат: 8

    a = Range(«A1:C5»)

    n = WorksheetFunction.Count(a)

MsgBox n  ‘Результат: 8

    n = WorksheetFunction.Count(«раз», «два», «три», 1, 2, 3)

MsgBox n  ‘Результат: 3

    n = WorksheetFunction.Count(«раз», «два», «три», «1», «2», «3», 1, 2, 3)

MsgBox n  ‘Результат: 6

    n = WorksheetFunction.Count(Empty, Empty, 0, 0, «», «»)

MsgBox n  ‘Результат: 4

    n = WorksheetFunction.Count(True, False, «True», «False»)

MsgBox n  ‘Результат: 2

End Sub

Метод WorksheetFunction.Count можно использовать для подсчета количества числовых значений в массиве, если он создан путем присвоения ему значений диапазона. Тогда логические значения ИСТИНА и ЛОЖЬ, если они встречаются в диапазоне, в подсчете количества числовых значений не участвуют.

Примеры с WorksheetFunction.CountA

Sub Primer2()

Dim n As Double, a() As Variant

    n = WorksheetFunction.CountA(Range(«A1:C5»))

MsgBox n  ‘Результат: 13

    a = Range(«A1:C5»)

    n = WorksheetFunction.CountA(a)

MsgBox n  ‘Результат: 15

    n = WorksheetFunction.CountA(«раз», «два», «три», 1, 2, 3)

MsgBox n  ‘Результат: 6

    n = WorksheetFunction.CountA(Empty, Empty, 0, 0, «», «»)

MsgBox n ‘Результат: 6

End Sub

Примеры с WorksheetFunction.CountBlank

Sub Primer3()

Dim n As Double, a As Range

    n = WorksheetFunction.CountBlank(Range(«A1:C5»))

MsgBox n  ‘Результат: 2

    Set a = Range(«A1:C5»)

    n = WorksheetFunction.CountBlank(a)

MsgBox n  ‘Результат: 2

End Sub

Следующая статья по этой теме: VBA Excel. Методы CountIf и CountIfs.


Andrey72

4 / 4 / 2

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

Сообщений: 62

1

29.04.2014, 13:31. Показов 11170. Ответов 4

Метки нет (Все метки)


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

Подскажите пожалуйста.
Есть код который определяет количество заполненных строк на листе:

VB.NET
1
Book.Worksheets(1).UsedRange.Rows.Count

вопросы:
1.Как определить количество заполненных ячеек в конкретной строке;
2.Как определить количество заполненных ячеек в конкретном столбце.
Надеюсь на вашу помощь.



0



Programming

Эксперт

94731 / 64177 / 26122

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

Сообщений: 116,782

29.04.2014, 13:31

4

Апострофф

Заблокирован

29.04.2014, 13:48

2

Лучший ответ Сообщение было отмечено Памирыч как решение

Решение

Цитата
Сообщение от GOOGLE

Для определения номера последней заполненной ячейки в конкретной строке или столбце можно воспользоваться свойством End об’екта Range и специальными константами xlToRight(= -4161), xlDown(=-4121)

Пример определения номера последней заполненной ячейки в конкретной строке и столбце.

Visual Basic
1
2
3
iRow = Columns(3).End(xlDown).Row 
iRow = Columns("C").End(xlDown).Row 
iClm = Rows(10).End(xlToRight).Column

Комментарий :
важно Этот вариант будет корректно работать только при условии, что данные в строке, или столбце начинаются с самой первой ячейки и не содержат пустых ячеек.

Вариант для Вашего случая

VB.NET
1
2
iRow = Book.Worksheets(1).Columns("C").End(xlDown).Row 
iClm = Book.Worksheets(1).Rows(10).End(xlToRight).Column



1



4 / 4 / 2

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

Сообщений: 62

29.04.2014, 14:01

 [ТС]

3

Благодарю, очень помогли и так быстро.
Наверно глупый вопрос задам, но подскажите еще что нужно включить или прописать в проекте чтобы он воспринимал такие константы типа xlDown, я все время пользовался числовыми шифрами (-4121)



0



Апострофф

Заблокирован

29.04.2014, 14:15

4

Раннее и позднее связывание, разберитесь с этим, примеров по теме в разделе много…



0



Andrey72

4 / 4 / 2

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

Сообщений: 62

01.05.2014, 18:33

 [ТС]

5

Возникла еще одна проблема, почему то код

VB.NET
1
iClm = Book.Worksheets(1).Rows(10).End(xlToRight).Column

приводит к неправильному отображению количества заполненных ячеек, так в некоторых строках книги Excel пишет что занято 16384 ячейки (все), удаление строки и даже создание нового листа приводит к такому же результату. Не пойму в чем дело

Добавлено через 16 минут
Опытным путем выяснил, что если заполнено в строке больше 1 ячейки (хотя бы 2) то все нормально отображает, а вот если 1 ячейка то не видит ее и показывает 16384



0



In this Article

  • COUNT WorksheetFunction
  • Assigning a Count result to a Variable
  • COUNT with a Range Object
  • COUNT Multiple Range Objects
  • Using COUNTA
  • Using COUNTBLANKS
  • Using the COUNTIF Function
  • Disadvantages of WorksheetFunction
    • Using the Formula Method
    • Using the FormulaR1C1 Method

This tutorial will show you how to use the Excel COUNT function in VBA

The VBA COUNT function is used to count the number of cells in your Worksheet that have values in them. It is accessed using the WorksheetFunction method in VBA.

COUNT WorksheetFunction

The WorksheetFunction object can be used to call most of the Excel functions that are available within the Insert Function dialog box in Excel. The COUNT function is one of them.

Sub TestCountFunctino
  Range("D33") = Application.WorksheetFunction.Count(Range("D1:D32"))
End Sub

vba count syntax

You are able to have up to 30 arguments in the COUNT function. Each of the arguments must refer to a range of cells.

This example below will count how many cells are populated with values are in cells D1 to D9

Sub TestCount()   
   Range("D10") = Application.WorksheetFunction.Count(Range("D1:D9"))
End Sub

The example below will count how many values are in a range in column D and in a range in column F. If you do not type the Application object, it will be assumed.

Sub TestCountMultiple()
   Range("G8") = WorksheetFunction.Count(Range("G2:G7"), Range("H2:H7"))
End Sub

Assigning a Count result to a Variable

You may want to use the result of your formula elsewhere in code rather than writing it directly back to and Excel Range.  If this is the case, you can assign the result to a variable to use later in your code.

Sub AssignCount()
   Dim result As Integer
'Assign the variable   
   result = WorksheetFunction.Count(Range("H2:H11"))
'Show the result
   MsgBox "The number of cells populated with values is " & result
End Sub

vba count values

COUNT with a Range Object

You can assign a group of cells to the Range object, and then use that Range object with the WorksheetFunction object.

Sub TestCountRange()
   Dim rng As Range
'assign the range of cells
   Set rng = Range("G2:G7")
'use the range in the  formula
   Range("G8") = WorksheetFunction.Count(rng)
'release the range object
  Set rng = Nothing
End Sub

COUNT Multiple Range Objects

Similarly, you can count how many cells are populated with values in multiple Range Objects.

Sub TestCountMultipleRanges() 
   Dim rngA As Range 
   Dim rngB as Range
'assign the range of cells 
   Set rngA = Range("D2:D10") 
   Set rngB = Range("E2:E10")   
'use the range in the formula 
Range("E11") = WorksheetFunction.Count(rngA, rngB)
 'release the range object
  Set rngA = Nothing 
  Set rngB = Nothing
End Sub

Using COUNTA

The count will only count the VALUES in cells, it will not count the cell if the cell has text in it. To count the cells which are populated with any sort of data, we would need to use the COUNTA function.

Sub TestCountA()
   Range("B8) = Application.WorksheetFunction.CountA(Range("B1:B6")) 
End Sub

In the example below, the COUNT function would return a zero as there are no values in column B, while it would return a 4 for column C. The COUNTA function however, would count the cells with Text in them and would return a value of 5 in column B while still returning a value of 4 in column C.

vba count diff counta

Using COUNTBLANKS

The COUNTBLANKS function will only count the Blank Cells in the Range of cells – ie cells that have no data in them at all.

Sub TestCountBlank()   
   Range("B8) = Application.WorksheetFunction.CountBlanks(Range("B1:B6")) 
End Sub

In the example below, column B has no blank cells while column C has one blank cell.

vba count diff count blanks

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

automacro

Learn More

Using the COUNTIF Function

Another worksheet function that can be used is the COUNTIF function.

Sub TestCountIf()
   Range("H14") = WorksheetFunction.CountIf(Range("H2:H10"), ">0")
   Range("H15") = WorksheetFunction.CountIf(Range("H2:H10"), ">100")
   Range("H16") = WorksheetFunction.CountIf(Range("H2:H10"), ">1000")
   Range("H17") = WorksheetFunction.CountIf(Range("H2:H10"), ">10000")
End Sub

The procedure above will only count the cells with values in them if the criteria is matched – greater than 0, greater than 100, greater than 1000 and greater than 10000.  You have to put the criteria within quotation marks for the formula to work correctly.

vba count countif eg

Disadvantages of WorksheetFunction

When you use the WorksheetFunction to count the values in a range in your worksheet, a static value is returned, not a flexible formula. This means that when your figures in Excel change, the value that has been returned by the WorksheetFunction will not change.

vba count static

In the example above, the procedure TestCount has counted up the cells in column H where a value is present.  As you can see in the formula bar, this result is a figure and not a formula.

If any of the values change therefore in the Range(H2:H12), the results in H14 will NOT change.

Instead of using the WorksheetFunction.Count, you can use VBA to apply a Count Function to a cell using the Formula or FormulaR1C1 methods.

Using the Formula Method

The formula method allows you to point specifically to a range of cells eg: H2:H12 as shown below.

Sub TestCountFormula
  Range("H14").Formula = "=Count(H2:H12)"
End Sub

vba formula test count formula

VBA Programming | Code Generator does work for you!

Using the FormulaR1C1 Method

The FromulaR1C1 method is more flexible in that it does not restrict you to a set range of cells. The example below will give us the same answer as the one above.

Sub TestCountFormula()
   Range("H14").Formula = "=Count(R[-9]C:R[-1]C)"
End Sub

vba count formula r1c1

However, to make the formula more flexible, we could amend the code to look like this:

Sub TestCountFormula() 
   ActiveCell.FormulaR1C1 = "=Count(R[-11]C:R[-1]C)" 
End Sub

Wherever you are in your worksheet, the formula will then count the values in the 12 cells directly above it and place the answer into your ActiveCell. The Range inside the COUNT function has to be referred to using the Row (R) and Column (C) syntax.

Both these methods enable you to use Dynamic Excel formulas within VBA.

There will now be a formula in H14 instead of a value.

Понравилась статья? Поделить с друзьями:
  • Посчитать залитые цветом ячейки в excel
  • Посчитать ежемесячный платеж в excel
  • Посчитать для ячейки в excel
  • Посчитать длительность в excel
  • Посчитать даты условие в excel