简体   繁体   中英

Get Excel Cell by row NUMBER and column LETTER

In VB.NET, using Interop.Excel, I need to access a cell based on a row number and column letter. I tried my luck with...

pages.title = DirectCast(wksht.Cells(rows, "D"), Excel.Range).Value

Since the parameters took type object, I figured maybe this would work, but got no luck. I also thought of enumerating each letter to a number, but the columns in the spreadsheet aren't as normal. Meaning, they're not

AB C DEFG

They're actually...

AB C DET AZ

I don't know if this makes a difference in the numbering of the columns. The question should be obvious, but just to reiterate, how can I get a cell based on a row number and column letter?

For a single cell:

wksht.Range(colLetter + rows)

MSDN link

Use the ASCII values of the characters as a "base" system

"A" = 1 = ASCII value of A - ASCII value of A + 1

"AA" = 27 = (ASCII value of A - ASCII value of A +1)* 26 + (ASCII value of A - ASCII value of A +1)

"BA" = (ASCII value of B - ASCII value of A + 1) * 26 + (ASCII value of A - ASCII value of A + 1)

etc., multiplying by 26 to the power of the (digit -1)

Function GetIndex(ByVal str As String) As Integer
        Dim i As Integer
        str = str.ToUpper()
        GetIndex = 0
        For i = str.Length - 1 To 0 Step -1
            GetIndex = GetIndex + (26 ^ (str.Length - i - 1)) * (Asc(str(i)) - Asc("A") + 1)
        Next
End Function

Try this:

Dim oWorksheet as Worksheet : Set oWorksheet = ActiveSheet

Dim iRow As Integer : iRow = 10
Dim strColumn as String : strColumn = "AZ"

Dim oCell as Range
Set oCell = oWorksheet.Cells(iRow, 1).Range(strColumn & "1")

oWorksheet.Cells(iRow, 1) gives you the first cell on the desired row, and .Range(strColumn & "1") gives you a horizontal offset from there based on the column letter(s).


EDIT : See Lance Roberts' answer for a much simpler solution.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM