我创建了一些用于 Excel 电子表格的 VBA 函数。现在,函数的参数具有 String 类型,因此我必须将列引用作为字符串传递。
但是,我更喜欢 R1C1 表示法(自 Multiplan 以来一直使用它),但我不知道如何使用该表示法将列引用传递给 VBA 函数。换句话说,我想定义一个函数,以便我可以通过以下方式调用它
=foo(C[-2])
所以我正在为以下功能寻找正确的类型
函数 foo(ColRef as WhatTypeGoesHere) ...
最佳答案
这将解释使用哪一个:)
Dim ws As Worksheet
Sub Sample()
Set ws = ThisWorkbook.Sheets("Sheet1")
Debug.Print foo1("B") '<~~ Col Name
Debug.Print foo2(Range("B1")) '<~~ Range
Debug.Print foo3(2) '<~~ Col Number
Debug.Print foo4("R1C2") '<~~ RC Notation
End Sub
Function foo1(ColRef As String) As Long
foo1 = ws.Cells(ws.Rows.Count, ColRef).End(xlUp).Row
End Function
Function foo2(ColRef As Range) As Long
foo2 = ws.Cells(ws.Rows.Count, ColRef.Column).End(xlUp).Row
End Function
Function foo3(ColRef As Integer) As Long
foo3 = ws.Cells(ws.Rows.Count, ColRef).End(xlUp).Row
End Function
Function foo4(ColRef As String) As Long
Dim MYAr
MYAr = Split(ColRef, "C", , vbTextCompare)
foo4 = ws.Cells(ws.Rows.Count, Val(MYAr(UBound(MYAr)))).End(xlUp).Row
End Function
截图
编辑:
需要注意的是“C[-2]”不是
Column B
它是当前单元格的偏移量。这是另一个可以处理不同 RC
的示例符号。请注意,我没有进行任何错误处理,但我相信您可以处理。这段代码的目的是展示如何使用 RC
找到最后一行。符号Dim ws As Worksheet
Sub Sample()
Set ws = ThisWorkbook.Sheets("Sheet1")
Debug.Print foo4("C[-2]")
Debug.Print foo4("RC[-2]")
Debug.Print foo4("R[-1]C[-2]")
End Sub
Function foo4(ColRef As String) As Long
Dim MYAr, sTmp As String
Dim colNo As Integer
Dim rng As Range
'~~> I am assuming that you will pass a `C`. If not then
'~~> Add an error handling here
MYAr = Split(ColRef, "C", , vbTextCompare)
If InStr(1, MYAr(UBound(MYAr)), "[") Then
tmpAr = Split(MYAr(UBound(MYAr)), "[")(1)
tmpAr = Split(tmpAr, "]")(0)
colNo = Val(Trim(tmpAr))
Else
colNo = MYAr(UBound(MYAr))
End If
Set rng = ActiveCell.Offset(, colNo)
foo4 = ws.Cells(ws.Rows.Count, rng.Column).End(xlUp).Row
End Function
关于vba - Excel R1C1 引用的类型是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20569668/