什么是Excel R1C1引用的TYPE?

时间:2013-12-13 15:08:49

标签: excel vba excel-vba

我创建了一些用于Excel电子表格的VBA函数。现在,函数的参数具有String类型,因此我必须将我的列引用作为字符串传递。

但是,我更喜欢R1C1表示法(自Multiplan以来一直使用它)但我无法弄清楚如何使用该表示法将列引用传递给VBA函数。换句话说,我想定义一个函数,所以我可以用以下方式调用它

= foo(C [-2])

所以我正在寻找以下功能的正确类型

function foo(ColRef as WhatTypeGoesHere)...

2 个答案:

答案 0 :(得分:3)

这将解释使用哪一个:)

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

答案 1 :(得分:1)

在您的情况下,请使用Range

您可以指定任何数据类型,Excel将根据需要隐式转换。这实际上取决于功能的作用。例如,如果函数使用一组单元格或单个单元格,则使用Range,如果函数删除字符,则使用String