请参考VBA功能中相邻表格列中的单元格

时间:2018-11-30 14:56:45

标签: excel vba excel-vba excel-formula

我试图在Excel VBA中创建一个函数,该函数引用该函数将在同一表和同一行中的相邻单元格。本质上,我正在试图找出一个VBA术语来表达以下内容常规Excel表参考:

[@[columnname]]

我只需要将此参考用于基本的IF语句。

我觉得这个问题的答案应该很明显,但我只是想不通。

image of dummy table
编辑:添加此图像以显示我想要做什么。我基本上想创建一个更加指定的if语句,该语句将检查与PIK或应计利息相同行(但在“操作类型”列中)的单元格中的值是否为“初始设置”。这是一个愚蠢的版本,但我只需要了解如何制作参考的概念即可。

根据我的需要编辑了响应代码(感谢顺便说一句):

`Function IfAdvance(ifTrue As Variant, ifFalse As Variant)

Dim c As Range, lo As ListObject, f As Range

Set c = Application.Caller 'or Application.ThisCell
                           ' = the cell containing the formula

For Each lo In c.Worksheet.ListObjects
    If Not Intersect(c, lo.DataBodyRange) Is Nothing Then

        'locate the column header of interest
        Set f = lo.HeaderRowRange.Find("Action Type", , xlValues, xlWhole)

        If f.Value = "Initial Set-Up" Then
            MyTableUDF = ifTrue
        Else
            MyTableUDF = ifFalse
        End If
        Exit Function
    End If
Next lo

MyTableUDF = "Not in a Table!"

End Function`

但不幸的是无法使它工作。

2 个答案:

答案 0 :(得分:0)

不清楚要做什么,但这是一个示例,听起来很像您的描述

Function MyTableUDF()

    Dim c As Range, lo As ListObject, f As Range

    Set c = Application.Caller 'or Application.ThisCell
                               ' = the cell containing the formula

    For Each lo In c.Worksheet.ListObjects
        If Not Intersect(c, lo.DataBodyRange) Is Nothing Then

            'locate the column header of interest
            Set f = lo.HeaderRowRange.Find("Col2", , xlValues, xlWhole)

            If Not f Is Nothing Then
                MyTableUDF = c.EntireRow.Cells(f.Column) / 2 'for example
            Else
                MyTableUDF = CVErr(xlErrNA)
            End If
            Exit Function
        End If
    Next lo

    MyTableUDF = "Not in a Table!"

End Function

答案 1 :(得分:0)

事实证明,我真正需要知道的唯一概念是application.caller。从那里,我能够找出当前行并将其绑定到特定列。感谢所有抽出宝贵时间的人!

Function IfInitialSetup(ifTrue As Variant, ifFalse As Variant)

Dim rownum As Long
Dim colnum As Long
Dim str As String

rownum = Application.Caller.row
colnum = Sheet3.Range("Table14[Action Types]").Column
str = Sheet3.Range(Sheet3.Cells(rownum, colnum).Address).Value

If str = "Initial Set-Up" Then
    IfInitialSetup = ifTrue
    Else
    IfInitialSetup = ifFalse
End If

End Function