如何在VBA中使用列字母
我目前正在努力解决以下问题
我试图实现一个用户可以input列的字符的input框。
之后,我不知道如何将其转换为一个数字,以在Worksheet.Cells
方法中使用它
例如 :用户input“B”,程序将其保存在一个名为x的variables中,并将其转换为一个数字,以便用作Worksheet.Cells(Row, X)
有没有什么方法,或有人有一个想法如何做到这一点?
Cells()是你的朋友。
不要过问这个。
Cells(1, 1) = "jello" ' changes cell A1 Cells(2, "AZ") = "too much jello" ' changes cell AZ2
Cells()的第二个参数可以是数字或alpha列标题。
B是第二列,所以你可以使用expression式(基于ASCII):
Sub main() Dim s As String s = "AB" example s End Sub Sub example(s As String) Dim colNum As Integer Dim i As Integer i = 1: colNum = 0 While (Mid(s, i, 1) <> "") colNum = colNum * 26 + (Asc(UCase(Mid(s, i, 1))) - Asc("A") + 1) i = i + 1 Wend MsgBox colNum End Sub
Function getColNum(colLetter As String) As Long On Error Resume Next 'will return 0 if letter > last col getColNum = Range(colLetter & "1").Column End Function