如何取得單元格範圍作為函數參數

如何取得單元格範圍作為函數參數

我正在嘗試製作一個簡單的宏,該宏應該循環遍歷給定的單元格範圍,並返回與某些內容匹配的單元格旁邊的單元格。

從一些論壇中,我發現了一條應該適用於單元格物件的行:

someCell.Offset(0,colIndex)

但從調試中我可以看到選擇的輸入資料是一組變體/字串而不是“單元格”物件。

我的函數有辦法獲取一系列單元格而不是變體/字串嗎?

還有我的完整程式碼:

Function RVLOOKUP(target, criteriaCellRange, colIndex)

    Dim found as Boolean
    Dim resultCell as Variant

    For Each cell In criteriaCellRange
        matchPosition = instr(target,cell)
        If matchPosition > 0 Then
            found = True
            resultCell = cell
            Exit For
        end if
    Next cell

    If found Then
        ' Here resultCell seems to be just a String not an actual cell object
        RVLOOKUP = resultCell.Offset(0,colIndex)
    else
        RVLOOKUP = "#NoMatch"
    end if

End Function

更新:程式碼假設從 criteriaCellRange 中尋找與儲存格目標中的文字完全或部分相符的儲存格,並傳回 criteriaCellRange 中的符合儲存格水平偏移量為 colIndex 的儲存格。所以基本上就是一個也符合部分文字的 VLOOKUP。

所以...這裡我們有同樣的問題,那裡的答案證實了我的懷疑:

當將單元格範圍作為函數的參數傳遞時,我相信該函數接收字串或值。零只是空白單元格的值。如果沒有看到您的程式碼,就很難為您的問題提出解決方案。

順便說一句,我正在使用 Libreoffice 5.4.4.2。

答案1

只需進行一些調整:

Function RVLOOKUP(target, criteriaCellRange, colIndex)

    Dim found As Boolean
    Dim resultCell As Range

    For Each cell In criteriaCellRange
        matchPosition = InStr(cell, target)
        If matchPosition > 0 Then
            found = True
            Set resultCell = cell
            Exit For
        End If
    Next cell

    If found Then
        ' Here resultCell seems to be just a String not an actual cell object
        RVLOOKUP = resultCell.Offset(0, colIndex)
    Else
        RVLOOKUP = "#NoMatch"
    End If

End Function

我顛倒了InStr()論點並做了resultCell一個範圍

答案2

來自物件導向文檔:

參數作為值傳遞

從 Calc 傳遞給巨集的參數總是值。不可能知道使用了哪些細胞(如果有的話)。例如,=PositiveSum(A3) 傳遞儲存格 A3 的值,而 PositiveSum 無法知道儲存格 A3 已被使用。如果您必須知道引用了哪些單元格而不是單元格中的值,請將範圍作為字串傳遞,解析該字串,並取得引用單元格中的值。

所以我想要達到的目標是不可能的。 :(

相關內容