Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Finding the number of non-blank columns in an Excel sheet using VBA

Tags:

excel

vba

How do I find the number of used columns in an Excel sheet using VBA?

Dim lastRow As Long lastRow = Sheet1.Range("A" & Rows.Count).End(xlUp).Row MsgBox lastRow 

Using the above VBA I'm able to find the number of rows. But how do I find the number of columns in my given excel file?

like image 988
niko Avatar asked Aug 01 '11 10:08

niko


People also ask

How do you count non blank columns in Excel VBA?

Both the Excel and VBA methods use the COUNTA function to count the number of non blank cells in a selected range. value1: Any value, cell reference or range of cells. value2: Any value, cell reference or range of cells. Note 1: In Excel 2007 and later the COUNTA function can accept up to 255 value arguments.

How do I count the number of non blank rows in Excel VBA?

If you want to count only nonblank cells, you can use this formula =COUNTA(A1:G11) (the range A1:G11 indicates the range you want to count the nonblank cells from, you can change it as you need), or you also can use this formula =COUNTIF(A1:G11,"<>").


1 Answers

Your example code gets the row number of the last non-blank cell in the current column, and can be rewritten as follows:

Dim lastRow As Long lastRow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Row MsgBox lastRow 

It is then easy to see that the equivalent code to get the column number of the last non-blank cell in the current row is:

Dim lastColumn As Long lastColumn = Sheet1.Cells(1, Columns.Count).End(xlToLeft).Column MsgBox lastColumn 

This may also be of use to you:

With Sheet1.UsedRange     MsgBox .Rows.Count & " rows and " & .Columns.Count & " columns" End With 

but be aware that if column A and/or row 1 are blank, then this will not yield the same result as the other examples above. For more, read up on the UsedRange property.

like image 155
Jean-François Corbett Avatar answered Oct 03 '22 16:10

Jean-François Corbett