vba - Excel R1C1 引用的类型是什么?

标签 vba excel

我创建了一些用于 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

截图

enter image description here

编辑:

需要注意的是“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/

相关文章:

vba - 如何在VBA中动态创建的ComboBox上创建Sub?

excel - 如果满足条件,则删除首字母

vba - 您可以复制工作表并保留对新工作表的引用吗?

excel - 如何以编程方式重新应用数据过滤器?

vba - 将事件处理程序分配给在 VBA 中动态创建的用户窗体上的控件

excel - 从工作表上的列表框中获取值

vba - 将选中的自动编号列表更改为word中的纯文本

VBA UDF 更改所有工作表上的值。怎么限制为1?

excel - 使用 3 列数据在 Excel 2010 中创建图表

excel - Excel中数字的条件格式(自定义格式)