Last not empty cell in row; Excel VBA

匿名 (未验证) 提交于 2019-12-03 01:57:01

问题:

I have an excel sheet in which I need to find the last non empty cell in a specific column.

How do I do this?

The below will select this for me, but it will select the first not empty cell, I need the last not empty cell in the row.

Worksheets("DTCs").Range("A29").End(xlToRight).Select

回答1:

I think it might work just search from the other direction, so something like:

Worksheets("DTCs").Range("IV29").End(xlToLeft).Select 

Though maybe the IV would need to be changed to something else depending on the version of Excel (this seems to work in 2003).



回答2:

I have expanded on my comment above to provide solutions that

  • do not use Select
  • cater for the last cell in row 1 being used
  • cater for the entire row being empty
  • cater for the entire row being full

The Find method in the second code is a far more direct method of establishing the first non-blank cell

This line Set rng1 = ws.Rows(1).Find("*", ws.[a1], xlValues, , xlByColumns, xlPrevious) says, start in cell A1 of Sheet "DTCa" then look backwards (ie from the last cell in row 1) in row1 by column looking for anything (the *). This method either find the last non blank or returns Nothing , ie an empty row

using xltoLeft with specific checks

Sub Method1() Dim ws As Worksheet Dim rng1 As Range Set ws = Sheets("DTCs") If ws.Cells(1, Columns.Count) = vbNullString Then     Set rng1 = ws.Cells(1, Columns.Count).End(xlToLeft)     If rng1.Column  1 Then         'return last used cell         MsgBox "rng1 contains " & rng1.Address(0, 0)     Else     If ws.[a1] = vbNullString Then             MsgBox ws.Name & " row1 is completely empty", vbCritical         Else             'true last used cell is A1             MsgBox "rng1 contains " & rng1.Address(0, 0)         End If     End If Else     'last cell is non-blank     MsgBox ws.Cells(1, Columns.Count) & " contains a value", vbCritical End If End Sub 

recommended

Sub Method2()     Dim ws As Worksheet     Dim rng1 As Range     Set ws = Sheets("DTCs")     Set rng1 = ws.Rows(1).Find("*", ws.[a1], xlFormulas, , xlByColumns, xlPrevious)     If Not rng1 Is Nothing Then         MsgBox "rng1 contains " & rng1.Address(0, 0)     Else         MsgBox ws.Name & " row1 is completely empty", vbCritical     End If End Sub 


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!