Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Excel VBA - find first empty column

Tags:

excel

vba

I know how to find last column with data:

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

But I would like to find first empty column, that is, in my case, somewhere before last column with data.

 firstemptycolumn = ?
like image 615
Creakush Coliko Avatar asked Nov 20 '17 13:11

Creakush Coliko


People also ask

How do you find empty columns in Excel VBA?

Use VBA to Check IF a Cell is EmptyStart with the function name “IsEmpty”. Specify the cell that you want to check. Use a message box or a cell to get the result value. In the end, run the code.

How do I find the first non empty cell in Excel VBA?

Find method in VBA. In this case, we will use the Range. Find method to start in the last cell in the worksheet, and set the SearchDirection parameter to xlNext . This then starts the search in the first cell in the worksheet (A1) and looks through each row until a non-blank cell is found.


2 Answers

Try like this for the first empty column of row 1:

finalcolumn  =  1 + .Cells(1, 1).End(xlToRight).Column

It is quite the same logic as your code, but you start from the left and you move to the right.


There are two cases, where this code will give wrong values:

  • if the last column with value is the last column in Excel ("XFD"), then it will return a column, that does not exist;

  • if there is no value on the first column at all, it will return the same - 16384 + 1.

Both can be checked this way, working only with Excel versions after Excel 2003:

Function GetFinalFirstColumn(wks As Worksheet) As Long

    GetFinalFirstColumn = 1 + wks.Cells(1, 1).End(xlToRight).Column
    
    'Case for empty first row
    'Case for column XFD
    If GetFinalFirstColumn = 2 ^ 14 + 1 Then
        GetFinalFirstColumn = -1
    End If
End Function
like image 104
Vityata Avatar answered Sep 30 '22 01:09

Vityata


You just need to add 1 to the last column found with data to find the first empty column.

finalcolumn = .Cells(1, .Columns.Count).End(xlToLeft).Column
firstemptycolumn = finalcolumn + 1
like image 43
Subodh Tiwari sktneer Avatar answered Sep 30 '22 01:09

Subodh Tiwari sktneer