Find last cell with values using indexes

断了今生、忘了曾经 提交于 2019-12-24 11:08:38

问题


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:


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.



来源:https://stackoverflow.com/questions/27225857/find-last-cell-with-values-using-indexes

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