Find last cell with values using indexes

2019-08-06 18:57发布

I try to find the last cell in a column that contains values. I know I can use something like:

Dim findme As Range = excel.Range("A1:A" & lastrow.row)

but I am looking for a way not to use this column-character format. Something like this VBA format

Dim rng as range
with myWorksheet
    LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row
    rng = .Range(.Cells(1,1), .Cells(LastRow, 1))
end with

1条回答
小情绪 Triste *
2楼-- · 2019-08-06 19:47

I created an helper class to solve this problem:

Imports Excel = Microsoft.Office.Interop.Excel

Public Class FindLastCellByIndex
    Private Shared Function getStringRangeFormat(ByVal colNumber As Long, ByVal rowNumber As Long) As String
        If colNumber > 0 AndAlso colNumber < 27 Then
            Dim c As Char
            c = Convert.ToChar(colNumber + 64)
            Return (c & rowNumber & ":" & c).ToString
        Else
            Return ""
        End If
    End Function

    Public Shared Function getSearchRange(ByRef _sheet As Excel.Worksheet, ByVal Col As Long, ByVal startRow As Long) As Excel.Range
        Dim strColCharSpez As String = getStringRangeFormat(Col, startRow)
       'Build String
        Dim rng As Excel.Range = DirectCast(_sheet.Cells(_sheet.Rows.Count, startRow), Excel.Range)
        Dim t As Long
        t = rng.End(Excel.XlDirection.xlUp).Row

        Return _sheet.Range(strColCharSpez & t)

    End Function
End Class

This is the way to use it:

Dim rng As Excel.Range = FindLastCellByIndex.getSearchRange(_sheet, 3, 3)

Now you get the Range: Range(Cells(3,3), Cells(LastRow, 3) as an object.

查看更多
登录 后发表回答