这里有两个解决方案。一个具有优雅的通用性,另一个简单直接针对 Excel 的当前实现。第一个仅受 Integer 或 Long 数据类型的精度限制。如果最大列数增加到超过 18278(列引用从三个字母变为四个字母的点),则第二个将失败。两者都是纯 VBA,不依赖于 MS Office 应用程序特有的功能。
列引用被视为给定位数的以 26 为基数的连续组,其中字母表用作数字 A=0、B=1、.. 等。首先有 26 个单字母列。然后 26^2 = 676 个双字母列,然后 26^3 = 17576 个三字母列,总共 18278 个,其中 Excel 只使用了 16384 个。
A1,B1,...,Z1 (1-26, 26 列)
AA1,....,ZZ1,(27 到 702, 26^2 = 676 列)
AAA1,...,XFD1 (703 到 16384, 15682 列 26^3 = 17576 可能有三个字母)
这是第一个解决方案。目前最大列数为 16384,因此代码将使用 Integer(上限 32767)代替 Long。如果您愿意,可以错误检查列参数 C 是否超出范围。
'
' A "pure" implementation limited only by precision of the Long integer data type
'
'
' The first step is to find how many letters are needed.
' the second is to translate the column index into 0..(26^n) - 1 range
' Finally render that value as a base 26 number using alphabet for digits
'
Public Function CoordToA1Cell(ByVal R As Long, ByVal C As Long) As String
Dim colRef As String
Dim cwork As Long
Dim n As Integer
'
Static e(0 To 6) As Long ' powers of 26
Static s(0 To 6) As Long ' index ranges for number of letters needed
If C <= 0 OR R <= 0 Then Exit Function
' initialize on first call
If e(0) = 0 Then ' first call
s(0) = 1
e(0) = 1
For n = 1 To UBound(s)
e(n) = 26 * e(n - 1)
s(n) = s(n - 1) + e(n)
Next n
End If
cwork = C
colRef = ""
'
' step one: discover how many letters are needed
'
n = 1
Do
If C < s(n) Then
n = n - 1
Exit Do
End If
n = n + 1
Loop
' step two: translate into 0..(26^n) - 1 interval
cwork = cwork - s(n)
'
' Step three: represent column index in base 26 using alphabet for digits
'
Do While n > 0
colRef = colRef & Chr(65 + cwork \ e(n))
cwork = cwork Mod e(n)
n = n - 1
Loop
' the final (or only) digit
colRef = colRef & Chr(65 + cwork)
CoordToA1Cell = colRef & R
End Function
这第二个很简单(“Quick and Dirty”),适用于当前的 Excel。当列引用从 3 到 4 个字母时,如果最大列数超过 18278,则需要认真修改。'
Public Function CoordToA1CellQAD(ByVal R As Long, ByVal C As Long) As String
Dim colRef As String
Dim cwork As Long
If C <= 0 OR R <= 0 Then Exit Function
cwork = C
If cwork <= 26 Then
colRef = Chr(64 + cwork)
ElseIf cwork <= 26 * 26 + 26 Then
cwork = cwork - (26 + 1)
colRef = Chr(65 + (cwork \ 26)) & Chr(65 + (cwork Mod 26))
'ElseIf cwork <= 26 * 26 * 26 + 26 * 26 + 26 Then ' theoretical limit for three letters, 17576
ElseIf cwork <= 16384 Then ' actual Excel limit for columns
cwork = cwork - (26 * 26 + 26 + 1)
colRef = Chr(65 + (cwork \ 676))
cwork = cwork Mod 676
colRef = colRef & Chr(65 + (cwork \ 26)) & Chr(65 + (cwork Mod 26))
Else ' overflow
Exit Function
End If
CoordToA1CellQAD = colRef & R
End Function