引用特定命名列中的值

Referencing a value in a particular named column

是否有 excel formula/VBA 脚本来引用具有特定列名称的列中的单元格值?

例如:将“# of fruit”列中的值乘以该行中第 "price of fruit" 列中的值。

通常这很容易通过单元格引用完成,但我需要使用特定的列名来完成,因为该列可能位于不同工作表的不同位置。我想将其编码为用户定义的函数,这样只要 header 名称相同,无论列在哪里都可以使用它。

感谢您的帮助!

如果像我想象的那样 "column name" 你指的是列的第一个单元格,你可能会像你说的那样搜索用户函数,然后执行操作:

Public Function myOperation(ByVal columnHeader1 As String, ByVal columnHeader2 As String) As Long

    'note: if you want to hardcode the values, you just need to remove the arguments from the brackets above and uncomment the following two lines of code: 

    'columnHeader1 = "# of fruits"
    'columnHeader2 = "price of fruit"      

    cnt1 = 1
    cnt2 = 1
    Do While ActiveSheet.Cells(1,cnt1).Value <> columnHeader1
        cnt1 = cnt1 + 1
    Loop     
    Do While ActiveSheet.Cells(1,cnt2).Value <> columnHeader2
        cnt2 = cnt2 + 1
    Loop   
    myOperation = ActiveSheet.Cells(Application.Caller.Row, cnt1).Value*ActiveSheet.Cells(Application.Caller.Row,cnt2).Value
End Function

在这种情况下,您需要在单元格中输入公式:

=myOperation("# of fruit", "price of fruit")

这将 return,在那个单元格中,两者之间的产品在同一行(我让你管理自定义)。请注意,您将需要一个错误处理(如果您输入一个不存在的名称,您可能会进入无限循环,请参阅 Christmas007 答案以了解如何在 Find 实际找到某些东西时进行陷阱)。

编辑

我已将 ActiveCell 替换为 Application.Caller,以使公式动态响应函数所在的调用方单元格。

这是硬编码值函数的样子:

Public Function myOperation() As Long

    columnHeader1 = "# of fruits"
    columnHeader2 = "price of fruit"

    cnt1 = 1
    cnt2 = 1
    Do While ActiveSheet.Cells(1, cnt1).Value <> columnHeader1
        cnt1 = cnt1 + 1
    Loop
    Do While ActiveSheet.Cells(1, cnt2).Value <> columnHeader2
        cnt2 = cnt2 + 1
    Loop
    myOperation = ActiveSheet.Cells(Application.Caller.Row, cnt1).Value * ActiveSheet.Cells(Application.Caller.Row, cnt2).Value
End Function

并通过简单的 =myOperation() 调用到单元格中。

为了后代的缘故,我将包括@fnostro 的评论中的回答,这是现场...

"That's not how things are done in Excel. Certainly you can do that by executing a search from within your function for that header and then act on the cells below it. but why would you design a spreadsheed with roaming column headers. Typically you would use Named Ranges and they would represent a fixed location within the workbook. but they can be anywhere and the function would always use the RangeName regardless of where it's been defined."

但是,您可以使用搜索来执行此操作:

Sub Macro1()

    Dim ColNum As Long, LastCol As Long

    LastCol = Cells(1, Columns.Count).End(xlToLeft).Column

    If Not Range(Cells(1, 1), Cells(1, LastCol)).Find("# of Fruit", LookIn:=xlValues, LookAt:=xlWhole) Is Nothing Then
        ColNum = Range(Cells(1, 1), Cells(1, LastCol)).Find("# of Fruit", LookIn:=xlValues, LookAt:=xlWhole).Column
    Else
        MsgBox "'# of Fruit' Not Found"
    End If

End Sub

ColNum 将是您对该列的引用。

编辑:如果 .Find 返回 Nothing,则忘记包含错误处理程序。现已修复。