Worksheetfunction counta vba excel

Подсчет количества ячеек в диапазоне в зависимости от их содержимого методами 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.


title keywords f1_keywords ms.prod api_name ms.assetid ms.date ms.localizationpriority

WorksheetFunction.CountA method (Excel)

vbaxl10.chm137142

vbaxl10.chm137142

excel

Excel.WorksheetFunction.CountA

b3d8662b-a886-daf8-2ce0-763017fbcd94

05/22/2019

medium

WorksheetFunction.CountA method (Excel)

Counts the number of cells that are not empty and the values within the list of arguments.

Syntax

expression.CountA (Arg1, Arg2, Arg3, Arg4, Arg5, Arg6, Arg7, Arg8, Arg9, Arg10, Arg11, Arg12, Arg13, Arg14, Arg15, Arg16, Arg17, Arg18, Arg19, Arg20, Arg21, Arg22, Arg23, Arg24, Arg25, Arg26, Arg27, Arg28, Arg29, Arg30)

expression A variable that represents a WorksheetFunction object.

Parameters

Name Required/Optional Data type Description
Arg1 — Arg30 Required Variant 1 to 30 arguments representing the values that you want to count.

Return value

Double

Remarks

Use CountA to count the number of cells that contain data in a range or array.

A value is any type of information, including error values and empty text («»). A value does not include empty cells.

If an argument is an array or reference, only values in that array or reference are used. Empty cells and text values in the array or reference are ignored.

If you don’t need to count logical values, text, or error values, use the Count function.

[!includeSupport and feedback]

Date yes Add (Subtract) Days to a Date Concatenate Dates Convert Date to Number Convert Date to Text Month Name to Number Create Date Range from Dates Day Number of Year Month Name from Date First Day of Month Add (Subtract) Weeks to a Date If Functions with Dates Max Date Number of Days Between Dates Number of Days in a Month Number of Weeks Between Dates Number of Years Between Dates Split Date & Time into Separate Cells Countdown Remaining Days Insert Dates Random Date Generator Using Dynamic Ranges — Year to Date Values Add (Subtract) Years to a Date Date Formula Examples Extract Day from Date Get Day Name from Date Count Days Left in Month / Year Count Workdays Left in Month / Year Get Last Day of Month Last Business Day of Month / Year Number of Work / Business Days in Month Weekday Abbreviations Auto Populate Dates Number of Months Between Dates Quarter from a Date Years of Service Change Date Format Compare Dates Time yes Add (Subtract) Hours to Time Add (Subtract) Minutes to Time Add (Subtract) Seconds to Time Add Up time (Total Time) Time Differences Change Time Format Convert Minutes to Hours Convert Time to Decimal Convert Time to Hours Convert Time to Minutes Convert Time to Seconds Military Time Round Time to Nearest 15 Minutes Overtime Calculator Number of Hours Between Times Convert Seconds to Minutes, Hours, or Time Count Hours Worked Time Differences Time Format — Show Minutes Seconds Text yes Add Commas to Cells Get First Word from Text Capitalize First Letter Clean & Format Phone #s Remove Extra Trailing / Leading Spaces Add Spaces to Cell Assign Number Value to Text Combine Cells with Comma Combine First and Last Names Convert Text String to Date Convert Text to Number Extract Text From Cell Get Last Word Remove Unwated Characters Extract Text Before or After Character How to Split Text String by Space, Comma, & More Remove Special Characters Remove First Characters from Left Substitute Multiple Values Switch First & Last Names w/ Commas Remove Specific Text from a Cell Extract Text Between Characters (Ex. Parenthesis) Add Leading Zeros to a Number Remove Line Breaks from Text Remove all Numbers from Text Reverse Text Remove Non-Numeric Characters Remove Last Character(s) From Right Separate First and Last Names Separate Text & Numbers Round yes Round Formulas Round Price to Nearest Dollar or Cent Round to Nearest 10, 100, or 1000 Round to Nearest 5 or .5 Round Percentages Round to Significant Figures Count yes Count Blank and Non-blank Cells Count Cells Between Two Numbers Count Cells not Equal to Count if Cells are in Range Count Times Word Appears in Cell Count Words in Cell Count Specific Characters in Column Count Total Number of Characters in Column Count Cells that Equal one of two Results Count Cells that do not Contain Count Cells that Contain Specific Text Count Unique Values in Range Countif — Multiple Criteria Count Total Number of Cells in Range Count Cells with Any Text Count Total Cells in a Table Lookup yes Two Dimensional VLOOKUP VLOOKUP Simple Example Vlookup — Multiple Matches Case Sensitive Lookup Case Sensitive VLOOKUP Sum if — VLOOKUP Case Sensitive Lookup Case Sensitive VLOOKUP Find Duplicates w/ VLOOKUP or MATCH INDEX MATCH MATCH Lookup — Return Cell Address (Not Value) Lookup Last Value in Column or Row Reverse VLOOKUP (Right to Left) Risk Score Bucket with VLOOKUP Sum with a VLOOKUP Function VLOOKUP & INDIRECT VLOOKUP Concatenate VLOOKUP Contains (Partial Match) 17 Reasons Why Your XLOOKUP is Not Working Double (Nested) XLOOKUP — Dynamic Columns IFERROR (& IFNA) XLOOKUP Lookup Min / Max Value Nested VLOOKUP Top 11 Alternatives to VLOOKUP (Updated 2022!) VLOOKUP – Dynamic Column Reference VLOOKUP – Fix #N/A Error VLOOKUP – Multiple Sheets at Once VLOOKUP & HLOOKUP Combined VLOOKUP & MATCH Combined VLOOKUP Between Worksheets or Spreadsheets VLOOKUP Duplicate Values VLOOKUP Letter Grades VLOOKUP Return Multiple Columns VLOOKUP Returns 0? Return Blank Instead VLOOKUP w/o #N/A Error XLOOKUP Multiple Sheets at Once XLOOKUP Between Worksheets or Spreadsheets XLOOKUP by Date XLOOKUP Duplicate Values XLOOKUP Multiple Criteria XLOOKUP Return Multiple Columns XLOOKUP Returns 0? Return Blank Instead XLOOKUP Text XLOOKUP with IF XLOOKUP With If Statement Misc. yes Sort Multiple Columns Use Cell Value in Formula Percentage Change Between Numbers Percentage Breakdown Rank Values Add Spaces to Cell CAGR Formula Average Time Decimal Part of Number Integer Part of a Number Compare Items in a List Dealing with NA() Errors Get Worksheet Name Wildcard Characters Hyperlink to Current Folder Compound Interest Formula Percentage Increase Create Random Groups Sort with the Small and Large Functions Non-volatile Function Alternatives Decrease a Number by a Percentage Calculate Percent Variance Profit Margin Calculator Convert Column Number to Letter Get Full Address of Named Range Insert File Name Insert Path Latitute / Longitude Functions Replace Negative Values Reverse List Range Convert State Name to Abbreviation Create Dynamic Hyperlinks Custom Sort List with Formula Data Validation — Custom Formulas Dynamic Sheet Reference (INDIRECT) Reference Cell in Another Sheet or Workbook Get Cell Value by Address Get Worksheet Name Increment Cell Reference List Sheet Names List Skipped Numbers in Sequence Return Address of Max Value in Range Search by Keywords Select Every Other (or Every nth) Row Basics yes Cell Reference Basics — A1, R1C1, 3d, etc. Add Up (Sum) Entire Column or Row Into to Dynamic Array Formulas Conversions yes Convert Time Zones Convert Celsius to Fahrenheit Convert Pounds to Kilograms Convert Time to Unix Time Convert Feet to Meters Convert Centimeters to Inches Convert Kilometers to Miles Convert Inches to Feet Convert Date to Julian Format Convert Column Letter to Number Tests yes Test if a Range Contains any Text Test if any Cell in Range is Number Test if a Cell Contains a Specific Value Test if Cell Contains Any Number Test if Cell Contains Specific Number Test if Cell is Number or Text If yes Percentile If Subtotal If Sumproduct If Large If and Small If Median If Concatentate If Max If Rank If TEXTJOIN If Sum yes Sum if — Begins With / Ends With Sum if — Month or Year to Date Sum if — By Year Sum if — Blank / Non-Blank Sum if — Horizontal Sum Count / Sum If — Cell Color INDIRECT Sum Sum If — Across Multiple Sheets Sum If — By Month Sum If — Cells Not Equal To Sum If — Not Blank Sum if — Between Values Sum If — Week Number Sum Text Sum if — By Category or Group Sum if — Cell Contains Specific Text (Wildcards) Sum if — Date Rnage Sum if — Dates Equal Sum if — Day of Week Sum if — Greater Than Sum if — Less Than Average yes Average Non-Zero Values Average If — Not Blank Average — Ignore 0 Average — Ignore Errors Math yes Multiplication Table Cube Roots nth Roots Square Numbers Square Roots Calculations yes Calculate a Ratio Calculate Age KILLLLLLL Calculate Loan Payments GPA Formula Calculate VAT Tax How to Grade Formulas Find yes Find a Number in a Column / Workbook Find Most Frequent Numbers Find Smallest n Values Find nth Occurance of Character in Text Find and Extract Number from String Find Earliest or Latest Date Based on Criteria Find First Cell with Any Value Find Last Row Find Last Row with Data Find Missing Values Find Largest n Values Most Frequent Number Conditional Formatting yes Conditional Format — Dates & Times Conditional Format — Highlight Blank Cells New Functions XLOOKUP Replaces VLOOKUP, HLOOKUP, and INDEX / MATCH Logical yes AND Checks whether all conditions are met. TRUE/FALSE IF If condition is met, do something, if not, do something else. IFERROR If result is an error then do something else. NOT Changes TRUE to FALSE and FALSE to TRUE. OR Checks whether any conditions are met. TRUE/FALSE XOR Checks whether one and only one condition is met. TRUE/FALSE Lookup & Reference yes FALSE The logical value: FALSE. TRUE The logical value: TRUE. ADDRESS Returns a cell address as text. AREAS Returns the number of areas in a reference. CHOOSE Chooses a value from a list based on it’s position number. COLUMN Returns the column number of a cell reference. COLUMNS Returns the number of columns in an array. HLOOKUP Lookup a value in the first row and return a value. HYPERLINK Creates a clickable link. INDEX Returns a value based on it’s column and row numbers. INDIRECT Creates a cell reference from text. LOOKUP Looks up values either horizontally or vertically. MATCH Searches for a value in a list and returns its position. OFFSET Creates a reference offset from a starting point. ROW Returns the row number of a cell reference. ROWS Returns the number of rows in an array. TRANSPOSE Flips the oriention of a range of cells. VLOOKUP Lookup a value in the first column and return a value. Date & Time yes DATE Returns a date from year, month, and day. DATEDIF Number of days, months or years between two dates. DATEVALUE Converts a date stored as text into a valid date DAY Returns the day as a number (1-31). DAYS Returns the number of days between two dates. DAYS360 Returns days between 2 dates in a 360 day year. EDATE Returns a date, n months away from a start date. EOMONTH Returns the last day of the month, n months away date. HOUR Returns the hour as a number (0-23). MINUTE Returns the minute as a number (0-59). MONTH Returns the month as a number (1-12). NETWORKDAYS Number of working days between 2 dates. NETWORKDAYS.INTL Working days between 2 dates, custom weekends. NOW Returns the current date and time. SECOND Returns the second as a number (0-59) TIME Returns the time from a hour, minute, and second. TIMEVALUE Converts a time stored as text into a valid time. TODAY Returns the current date. WEEKDAY Returns the day of the week as a number (1-7). WEEKNUM Returns the week number in a year (1-52). WORKDAY The date n working days from a date. WORKDAY.INTL The date n working days from a date, custom weekends. YEAR Returns the year. YEARFRAC Returns the fraction of a year between 2 dates. Engineering yes CONVERT Convert number from one unit to another. Financial yes FV Calculates the future value. PV Calculates the present value. NPER Calculates the total number of payment periods. PMT Calculates the payment amount. RATE Calculates the interest Rate. NPV Calculates the net present value. IRR The internal rate of return for a set of periodic CFs. XIRR The internal rate of return for a set of non-periodic CFs. PRICE Calculates the price of a bond. YIELD Calculates the bond yield. INTRATE The interest rate of a fully invested security. Information yes CELL Returns information about a cell. ERROR.TYPE Returns a value representing the cell error. ISBLANK Test if cell is blank. TRUE/FALSE ISERR Test if cell value is an error, ignores #N/A. TRUE/FALSE ISERROR Test if cell value is an error. TRUE/FALSE ISEVEN Test if cell value is even. TRUE/FALSE ISFORMULA Test if cell is a formula. TRUE/FALSE ISLOGICAL Test if cell is logical (TRUE or FALSE). TRUE/FALSE ISNA Test if cell value is #N/A. TRUE/FALSE ISNONTEXT Test if cell is not text (blank cells are not text). TRUE/FALSE ISNUMBER Test if cell is a number. TRUE/FALSE ISODD Test if cell value is odd. TRUE/FALSE ISREF Test if cell value is a reference. TRUE/FALSE ISTEXT Test if cell is text. TRUE/FALSE N Converts a value to a number. NA Returns the error: #N/A. TYPE Returns the type of value in a cell. Math yes ABS Calculates the absolute value of a number. AGGREGATE Define and perform calculations for a database or a list. CEILING Rounds a number up, to the nearest specified multiple. COS Returns the cosine of an angle. DEGREES Converts radians to degrees. DSUM Sums database records that meet certain criteria. EVEN Rounds to the nearest even integer. EXP Calculates the exponential value for a given number. FACT Returns the factorial. FLOOR Rounds a number down, to the nearest specified multiple. GCD Returns the greatest common divisor. INT Rounds a number down to the nearest integer. LCM Returns the least common multiple. LN Returns the natural logarithm of a number. LOG Returns the logarithm of a number to a specified base. LOG10 Returns the base-10 logarithm of a number. MOD Returns the remainder after dividing. MROUND Rounds a number to a specified multiple. ODD Rounds to the nearest odd integer. PI The value of PI. POWER Calculates a number raised to a power. PRODUCT Multiplies an array of numbers. QUOTIENT Returns the integer result of division. RADIANS Converts an angle into radians. RAND Calculates a random number between 0 and 1. RANDBETWEEN Calculates a random number between two numbers. ROUND Rounds a number to a specified number of digits. ROUNDDOWN Rounds a number down (towards zero). ROUNDUP Rounds a number up (away from zero). SIGN Returns the sign of a number. SIN Returns the sine of an angle. SQRT Calculates the square root of a number. SUBTOTAL Returns a summary statistic for a series of data. SUM Adds numbers together. SUMIF Sums numbers that meet a criteria. SUMIFS Sums numbers that meet multiple criteria. SUMPRODUCT Multiplies arrays of numbers and sums the resultant array. TAN Returns the tangent of an angle. TRUNC Truncates a number to a specific number of digits. Stats yes AVERAGE Averages numbers. AVERAGEA Averages numbers. Includes text & FALSE =0, TRUE =1. AVERAGEIF Averages numbers that meet a criteria. AVERAGEIFS Averages numbers that meet multiple criteria. CORREL Calculates the correlation of two series. COUNT Counts cells that contain a number. COUNTA Count cells that are non-blank. COUNTBLANK Counts cells that are blank. COUNTIF Counts cells that meet a criteria. COUNTIFS Counts cells that meet multiple criteria. FORECAST Predict future y-values from linear trend line. FREQUENCY Counts values that fall within specified ranges. GROWTH Calculates Y values based on exponential growth. INTERCEPT Calculates the Y intercept for a best-fit line. LARGE Returns the kth largest value. LINEST Returns statistics about a trendline. MAX Returns the largest number. MEDIAN Returns the median number. MIN Returns the smallest number. MODE Returns the most common number. PERCENTILE Returns the kth percentile. PERCENTILE.INC Returns the kth percentile. Where k is inclusive. PERCENTILE.EXC Returns the kth percentile. Where k is exclusive. QUARTILE Returns the specified quartile value. QUARTILE.INC Returns the specified quartile value. Inclusive. QUARTILE.EXC Returns the specified quartile value. Exclusive. RANK Rank of a number within a series. RANK.AVG Rank of a number within a series. Averages. RANK.EQ Rank of a number within a series. Top Rank. SLOPE Calculates the slope from linear regression. SMALL Returns the kth smallest value. STDEV Calculates the standard deviation. STDEV.P Calculates the SD of an entire population. STDEV.S Calculates the SD of a sample. STDEVP Calculates the SD of an entire population TREND Calculates Y values based on a trendline. Text yes CHAR Returns a character specified by a code. CLEAN Removes all non-printable characters. CODE Returns the numeric code for a character. CONCATENATE Combines text together. DOLLAR Converts a number to text in currency format. EXACT Test if cells are exactly equal. Case-sensitive. TRUE/FALSE FIND Locates position of text within a cell.Case-sensitive. LEFT Truncates text a number of characters from the left. LEN Counts number of characters in text. LOWER Converts text to lower case. MID Extracts text from the middle of a cell. PROPER Converts text to proper case. REPLACE Replaces text based on it’s location. REPT Repeats text a number of times. RIGHT Truncates text a number of characters from the right. SEARCH Locates position of text within a cell.Not Case-sensitive. SUBSTITUTE Finds and replaces text. Case-sensitive. TEXT Converts a value into text with a specific number format. TRIM Removes all extra spaces from text. UPPER Converts text to upper case. VALUE Converts a number stored as text into a number.

VBA COUNTA

Excel VBA COUNTA Function

You may have often used the COUNT and COUNTA functions within Microsoft Excel. Wherein COUNT captures all the numerical values in a cell, COUNTA captures all the non-empty cells (including strings). Is by any means possible to use COUNTA function through VBA? Absolutely, YES! You can use the COUNTA function through VBA as a worksheet function (as it is a part of WorksheetFunction family inside VBA) to count the non-empty cells through a given worksheet range. The benefit of COUNTA over COUNT function is – it can count anything (numbers, strings, special characters, Error-values, etc.) except empty cells in a given range whereas, COUNT can only count the number of cells that consist the numeric values.

VBA COUNTA Syntax:

The syntax for VBA COUNTA function is as shown below:

Syntax of COUNTA

Where,

Arg1 – Specifies the argument for this function which is mandatory and can take any non-empty value such as number, string, error values (like #N/A, #DIV/0!), special characters, etc. rest other arguments are optional.

This function can take a maximum of 30 arguments in a single call. An argument can consist of a range of cells or a single value which is inputted manually.

How to Use COUNTA Function in Excel VBA?

Below are the different examples to use COUNTA Function in Excel using VBA Code.

You can download this VBA COUNTA Excel Template here – VBA COUNTA Excel Template

Example #1 – VBA COUNTA with Manual Arguments as an Input

We will see how COUNTA function works when we provide manual arguments to it in VBA. Follow the below-mentioned steps:

Step 1: Insert a new module in Visual Basic Editor (VBE). Click on Insert tab > select Module.

VBA COUNTA Example 1-1

Step 2: Define a new sub-procedure within the newly inserted module, that can hold your macro.

Code:

Sub Example_1()

End Sub

VBA COUNTA Example 1-2

Step 3: Decide where we want to store the output for the COUNTA function. I want to store it in cell A2 of sheet named “Example 1”. In order to do that, we need to use Sheets.Range method in VBA. See the following screenshot for your reference:

Code:

Sub Example_1()

Sheets("Example 1").Range("A2")

End Sub

VBA COUNTA Example 1-3

This piece of code selects the cell A2 as a range from the sheet named Example 1.

Step 4: Use an assignment operator so that we can assign the value to the cell that is going to be accessed through the code above. Add the object named WorksheetFunction so that we can access COUNTA function under it.

Code:

Sub Example_1()

Sheets("Example 1").Range("A2") = WorksheetFunction

End Sub

VBA COUNTA Example 1-4

Step 5: Put a dot (.) after object specified and you will see a list of functions available to use under it. Select COUNTA from the list of multiple available functions which allows you to count the non-empty cells or values.

VBA COUNTA Example 1-5

Step 6: Specify the arguments manually under the COUNTA function. Arguments are: “Rajnish”, “#N/A”, 1, “*”, True. We have tried to bring all the data types as an argument to this function.

Code:

Sub Example_1()

Sheets("Example 1").Range("A2") = WorksheetFunction.CountA("Rajnish", "#N/A", 1, "*", True)

End Sub

VBA COUNTA Example 1-6

Step 7: Run this piece of code by hitting F5 or Run button and see the output under cell A2 of sheet “Example 1” in the active workbook.

VBA COUNTA Example 1-7

In this code, we want the system to count the input arguments and store the count under cell A2 of sheet Example 1.

Example #2 – VBA COUNTA to Count Non-Empty Cells in a Given Range

Suppose I have data all across column A and I need to count what are the non-empty rows in the entire column. As the entire column consists of more than 10 Lac’s rows, it is an ideal time-consuming for me to navigate towards and count each non-empty cell. See the partial screenshot of the data below.

VBA COUNTA Example 2-1

Follow the below steps:

Step 1: Define a new sub-procedure which can hold your macro.

Code:

Sub Example_2()

End Sub

VBA COUNTA Example 2-2

Step 2: Define two new variables under this sub-procedure as a Range using Dim. One variable will be helpful to hold the range of input argument column and other variables will be helpful in holding the cell where we want the output as a counted number.

Code:

Sub Example_2()

Dim rng_1 As Range
Dim op_cell As Range

End Sub

Define two new variables

Here, rng_1 will store the input range for COUNTA function. The output of COUNTA will be stored under op_cell variable.

Step 3: Now, set the range for both of the variables using VBA Set property. This is to be done because we can’t directly assign a value to a variable defined as a range object.

Code:

Sub Example_2()

Dim rng_1 As Range
Dim op_cell As Range
Set rng_1 = Range("A:A")
Set op_cell = Range("B1")

End Sub

Set the range

Here, rng_1 variable has been set to the range of entire column named A. op_cell is set to cell B1 as it would be the cell that contains the output of the COUNTA.

Step 4: Now, use general assignment operator against op_cell variable, so that we can store the output under the cell which is set to that variable. This can be considered as an output initialization.

Code:

Sub Example_2()

Dim rng_1 As Range
Dim op_cell As Range
Set rng_1 = Range("A:A")
Set op_cell = Range("B1")
op_cell =

End Sub

Output initialization

Step 5: Use WorksheetFunction object on the right-hand side of assignment operator (it would be an expression that will get evaluated and value will be stored under cell set to variable op_cell) to initialize the class within which we can access as well as use COUNTA function.

Code:

Sub Example_2()

Dim rng_1 As Range
Dim op_cell As Range
Set rng_1 = Range("A:A")
Set op_cell = Range("B1")
op_cell = WorksheetFunction

End Sub

Use WorksheetFunction

Step 6: As soon as you hit dot (.) after WorksheetFunction object, you can access all the functions available under that class. Navigate towards the COUNTA function and double click it to select.

VBA COUNTA Example 2-7

Step 7: Use rng_1 variable as an input argument under COUNTA. Therefore, this function under worksheet function object class can count the non-empty cells present within the entire column A.

Code:

Sub Example_2()

Dim rng_1 As Range
Dim op_cell As Range
Set rng_1 = Range("A:A")
Set op_cell = Range("B1")
op_cell = WorksheetFunction.CountA(rng_1)

End Sub

Use rng_1 variable

Step 8: Run this code by hitting the F5 or Run button and you can see the output as shown below in cell B1 of an active sheet from the workbook.

VBA COUNTA Example 2-9

In cell B1 we can see a number as 17. Which means that, we have 17 non-empty cells present in column A of the worksheet. You may not be seeing at all the 17 through this screenshot as it is a partial one. You better could see the worksheet and navigate through column A.

Things to Remember

  • You can use VBA COUNTA function when you have to count the number of non-empty cells present in the given range.
  • COUNTA considers all the values like numbers, strings, error values, Booleans, empty text (“”). However, it does not consider the cell which is empty.
  • The empty cells will not be counted using the COUNTA function and will be ignored.
  • You can use arguments manually in the VBA COUNTA function and it still works.

Recommended Articles

This is a guide to VBA COUNTA Function. Here we discuss how to use COUNTA Function in Excel VBA along with practical examples and downloadable excel template. You can also go through our other suggested articles –

  1. VBA Collection
  2. FileCopy in VBA
  3. Count Cells with Text in Excel
  4. VBA Get Cell Value

COUNTA Worksheet Function in Excel VBA

In our earlier article “Excel COUNTAThe COUNTA function is an inbuilt statistical excel function that counts the number of non-blank cells (not empty) in a cell range or the cell reference. For example, cells A1 and A3 contain values but, cell A2 is empty. The formula “=COUNTA(A1,A2,A3)” returns 2.
read more
,” we have seen how to use the COUNT function to count the numerical values from the range of values. How about calculating all the costs in the field of cells? Yes, we can estimate that as well. To count all the cell values in the range of cells, we need to use the formula “COUNTA” in Excel VBA. This article will show you how to use the COUNTA function in VBA to count all the cell values in the supplied range.

Table of contents
  • COUNTA Worksheet Function in Excel VBA
    • Examples of COUNTA Function in VBA
    • Coding with Variables
    • Recommended Articles

VBA-Counta-Function

You are free to use this image on your website, templates, etc, Please provide us with an attribution linkArticle Link to be Hyperlinked
For eg:
Source: VBA COUNTA (wallstreetmojo.com)

Examples of COUNTA Function in VBA

One truth is that the COUNTA function is not a VBA functionVBA functions serve the primary purpose to carry out specific calculations and to return a value. Therefore, in VBA, we use syntax to specify the parameters and data type while defining the function. Such functions are called user-defined functions.read more. So your question is if it is not a VBA function, how do we use it? Nothing worries, even though it is not a VBA function; still, we can use it under the worksheet function class in VBA coding.

You can download this VBA COUNTA Excel Template here – VBA COUNTA Excel Template

Let us write the code to apply the Excel VBA COUNTA.

Step 1: Create a subprocedure name.

Step 2: Now, decide where we will store the result of the VBA COUNTA function. In this example, I want to keep the work in cell C2. So my code will be Range(“C2”).Value.

Code:

Sub Counta_Example1()

 Range("C2").Value =

End Sub

VBA Counta Example 1

Step 3: In cell C2, we need the value of the VBA COUNTA function. So, to apply the Excel VBA COUNTA function, let’s first use the worksheet function class.

Code:

Sub Counta_Example1()

 Range("C2").Value = Work

End Sub

VBA Counta Example 1-1

Step 4: After applying the worksheet function class, select the formula COUNTA by putting a dot.

Code:

Sub Counta_Example1()

 Range("C2").Value = WorksheetFunction.Count

End Sub

VBA Counta Example 1-2

Step 5: We need to supply the range of cells for counting. In this example, we need to calculate the range of cells from A1 to A11. Then, to provide the cells using the VBA RANGE objectRange is a property in VBA that helps specify a particular cell, a range of cells, a row, a column, or a three-dimensional range. In the context of the Excel worksheet, the VBA range object includes a single cell or multiple cells spread across various rows and columns.read more.

Code:

Sub Counta_Example1()

 Range("C2").Value = WorksheetFunction.CountA(Range("A1:A11"))

End Sub

VBA Counta Example 1-3

Let us run the code to get the result in cell C2.

VBA Counta Example 1-4

So, the VBA COUNTA returns the same result as well.

Like this, we can use COUNTA to count the non-empty or non-blank cells from the supplied range.

Coding with Variables

VBA variables are the key to building a project. Now, we can declare VBA variablesVariable declaration is necessary in VBA to define a variable for a specific data type so that it can hold values; any variable that is not defined in VBA cannot hold values.read more and arrive at the result for the same data.

For example, look at the below code.

Code:

Sub Counta_Example2()

 Dim CountaRange As Range
 Dim CountaResultCell As Range

 Set CountaRange = Range("A1:A11")
 Set CountaResultCell = Range("C2")

 CountaResultCell = WorksheetFunction.CountA(CountaRange)

End Sub

Let us explain the above code now.

First, we have declared the variable “CountaRange” as a range to reference the range of values.

Dim CountaRange As Range

Next, we have set the reference as range A1 to A11.

Set CountaRange = Range("A1:A11")

The second variable is to reference the COUNTA result cell.

Dim CountaResultCell As Range

For this variable, we have set the cell as C2.

Set CountaResultCell = Range("C2")

As usual, we have applied the COUNTA function using variables instead of hardcoded ranges. Now, look at the old code and this VBA codeVBA code refers to a set of instructions written by the user in the Visual Basic Applications programming language on a Visual Basic Editor (VBE) to perform a specific task.read more.

Code 1:

Code 1

Code 2:

Code 2

In code 1, we have Range C2. In Code 2, we have the variable name “CountaResultCell.” Here the variable “CountaResultCell” set reference as a C2 cell. So this variable is a C2 cell now.

In code 1, the COUNTA function range is A1 to A11. In regulation 2, it is a variable called “CountaRange.” This variable holds a reference to the range A1 to A11.

That is the difference between old code and code with variables.

So, the COUNTA function helps us count all the non-empty cells from the supplied range irrespective of the data.

Recommended Articles

This article has been a guide to VBA COUNTA. Here, we learn how to use the COUNTA worksheet function in Excel VBA and examples and download an Excel template. Below are some useful Excel articles related to VBA: –

  • Exit Subprocedure in Excel VBA
  • Declare One Dimensional Array in VBA
  • Val Functions in VBA
  • COUNTIF Function in VBA

Like this post? Please share to your friends:
  • Worksheet word order in sentences
  • Working with function in excel
  • Worksheet vba excel свойства
  • Working with family word
  • Worksheet vba excel описание