Excel.Application.Cells.SpecialCells(xlCellTypeLastCell) returning bottom of worksheet, not last data cell

人盡茶涼 提交于 2019-11-28 00:34:37
Dan Wagner

(Too much info to use a comment here.)

VBA mastermind Ron de Bruin wrote a little snipped about why xlCellTypeLastCell as well as UsedRange might be failing here: http://www.rondebruin.nl/win/s9/win005.htm.

(In the post I linked to in my initial comment, Error in finding last used cell in VBA, the pitfalls of UsedRange are described in the same way.)

Here's the direct quote:

Possible problems with xlCellTypeLastCell and UsedRange are:

The last cell will only re-set when you save (or save/close/reopen the file). If cell formatting is changed it will not reset the last cell, clearing the data is not enough, you must delete the rows or columns then, See: http://www.contextures.com/xlfaqApp.html#Unused

To make a long story short, the logic for finding the last row on a sheet belongs inside a global function. You will use this function all the time. Here's an example for finding the last row on a sheet:

''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''''
'INPUT       : Sheet, the worksheet we'll search to find the last row
'OUTPUT      : Long, the last occupied row
'SPECIAL CASE: if Sheet is empty, return 1
'EXAMPLES    :
' 
'assume that there is a single 
'entry on MySheet in cell A5:
'
'LastRowNum(MySheet)
'>> 5
'
'assume that EmptySheet is totally empty:
'
'LastRowNum(EmptySheet)
'>> 1
'
Public Function LastRowNum(Sheet As Worksheet) As Long
    If Application.WorksheetFunction.CountA(Sheet.Cells) <> 0 Then
        LastRowNum = Sheet.Cells.Find(What:="*", _
                        LookIn:=xlFormulas, _
                        SearchOrder:=xlByRows, _
                        SearchDirection:=xlPrevious).Row
    Else
        LastRowNum = 1
    End If
End Function

As far as the downvote goes -- no idea. I've actually never downvoted here haha.

Christopher Teoh

Try using the following code to determine the last row & column instead

Dim LastCol As Long

Dim LastRow As Long

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

LastRow = ActiveSheet.Cells(Rows.Count, "A").End(xlUp).Row
Torres Viejo

You can try this:

Dim xlastcel As Range  
On Error Resume Next  
   ActiveSheet.ShowAllData: Err.Clear  ' Show All  
   ActiveSheet.UsedRange               ' Ajust Vertical Scrool  
   With ActiveSheet:  Set xlastcell = .Cells.Find(What:="*", After:=.[A1], SearchDirection:=xlPrevious): End With  
   If Err.Number > 0 Then MsgBox "Sheet without data", vbOKOnly  
On Error GoTo 0  
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!