首页 > 解决方案 > LibreOffice Calc:我可以从 VLOOKUP 获取单元格地址吗?

问题描述

我在 Calc 中使用 VLOOKUP,如下所示:

VLOOKUP(B11,G2:J7,4,0)

通常,当我们中的任何人使用它时,我们希望获取此函数找到的单元格中的值。在这种情况下,而不是值,我想获取一个包含单元格地址的字符串,或者该单元格的行和列。例如,如果我在单元格 J5 中有一个 30.14 的双精度浮点值,这就是答案,而不是让它返回 30.14,我希望它返回类似“J5”或 9,4 之类的东西或其他方式让我在宏中读取结果。

我试过使用 =ADDRESS() 和 =CELL("address", ) 但我遇到错误(=CELL() 给我 '#REF!')。


编辑:我使用这个例程作为 VLOOKUP 的包装器,带有一个浮点数表(这就是为什么它返回一个 DOUBLE 而不是将单元格值作为字符串或其他东西)。我所要做的就是将我想要从中获取数据的列传递给它:

Function getLookup(valColumn as Integer) as Double
    oDoc = ThisComponent
    oSheet = oDoc.Sheets (workSheet)
    rangeInfo = lookupTopLeft + ":" + lookupBottomRight
    cellRange = oSheet.getCellRangeByName(rangeInfo)
    oCell = oSheet.GetCellByPosition(dataCellColumn, dataCellRow)
    searchValue = oCell.getString()
    Mode = 0
    svc = createUnoService( "com.sun.star.sheet.FunctionAccess" )
    args = Array(searchValue, cellRange, valColumn, Mode)
    getLookup = svc.callFunction("VLOOKUP", args)
End Function

注意我在这里使用了一些局部变量。它们是私有的,仅用于模块,因此我在设计电子表格时不必在多个位置更改单元格引用。“lookupTopLeft”和“lookupBottomRight”是“G2”和“J7”,我正在使用的数据的左上角和右下角单元格。“dataCellColumn”和“dataCellRow”是我在 VLOOKUP 中使用的键的源的列和行坐标。

(@JohnSUN,我认为这可能会根据您在某处提供的答案进行修改。)

我希望能够执行类似的包装例程,该例程将返回单元格的列和行,而不是单元格中的值。

标签: spreadsheetlibreofficecalc

解决方案


许多可能的选项之一:

Option Explicit 

Const lookupTopLeft = "G2" 
Const lookupBottomRight = "J7"
Const dataCellColumn = 1
Const dataCellRow = 10
Const workSheet = 0

Function getCellByLookup(valColumn As Integer) As Variant
Dim oSheet As Variant, cellRange As Variant, oCell As Variant
Dim oColumnToSearch As Variant
Dim oSearchDescriptor As Variant
Dim searchValue As String 
Dim nRow As Long
    oSheet = ThisComponent.getSheets().getByIndex(workSheet)
    cellRange = oSheet.getCellRangeByName(lookupTopLeft + ":" + lookupBottomRight)
    searchValue = oSheet.GetCellByPosition(dataCellColumn, dataCellRow).getString()
    
Rem If we are looking not for a value, but for a cell, 
Rem then using VLOOKUP is unnecessary, a simple Find is enough  
    oColumnToSearch = cellRange.getCellRangeByPosition(0, 0, 0, _
        cellRange.getRows().getCount()-1) ' Resize full range to one first column
Rem Set search params
    oSearchDescriptor = oColumnToSearch.createSearchDescriptor()
    oSearchDescriptor.setSearchString(searchValue)
    oSearchDescriptor.SearchType = 1 ' Search in Values!
Rem Try to find searchValue in oColumnToSearch
    oCell = oColumnToSearch.findFirst(oSearchDescriptor)
    If Not IsNull(oCell) Then ' Only if the value was found
        nRow = oCell.getRangeAddress().StartRow
Rem Offset oCell to valColumn
        oCell = cellRange.getColumns().getByIndex(valColumn-1).GetCellByPosition(0,nRow)
        getCellByLookup = Replace(oCell.AbsoluteName, "$", "")
    Else    ' If the value from B11 is not found - warn about it
        getCellByLookup = "Not found"
    EndIf
End Function

推荐阅读