2024-01-04|閱讀時間 ‧ 約 25 分鐘

Excel函數撰寫

    一個EXCEL比對函數

    Excel VBA中創建一個自定義函數,用於比對兩個儲存格範圍的數據。這個示例函數將返回符合指定比對條件的數量。vba

    Function CompareRanges(sourceRange As Range, targetRange As Range, criteria As String) As Long
    Dim sourceCell As Range
    Dim targetCell As Range
    Dim countMatches As Long

    countMatches = 0

    ' 檢查比對條件是否合法
    If criteria <> "=" And criteria <> "<" And criteria <> ">" Then
    CompareRanges = CVErr(xlErrValue) ' 返回錯誤值
    Exit Function
    End If

    ' 開始比對
    For Each sourceCell In sourceRange
    For Each targetCell In targetRange
    If criteria = "=" And sourceCell.Value = targetCell.Value Then
    countMatches = countMatches + 1
    ElseIf criteria = "<" And sourceCell.Value < targetCell.Value Then
    countMatches = countMatches + 1
    ElseIf criteria = ">" And sourceCell.Value > targetCell.Value Then
    countMatches = countMatches + 1
    End If
    Next targetCell
    Next sourceCell

    CompareRanges = countMatches ' 返回符合比對條件的數量
    End Function






    使用這個自定義函數的示例:

    1. 打開Excel工作簿。
    2. 在一個儲存格中輸入比對條件,例如"="。
    3. 在另一個儲存格中輸入以下函數:=CompareRanges(A1:A10, B1:B10, C1)
    4. less
    =CompareRanges(A1:A10, B1:B10, C1)


    其中,A1:A10是源範圍,B1:B10是目標範圍,C1是比對條件。按下Enter鍵,函數將計算並返回符合比對條件的數量。

    這個示例中,我們創建了一個名為"CompareRanges"的自定義函數,它接受三個參數:源範圍、目標範圍和比對條件。根據比對條件,它將比對這兩個範圍的數據,並返回符合條件的數量。請確保在Excel中啟用了宏,以便使用這個自定義函數。

    分享至
    成為作者繼續創作的動力吧!
    從 Google News 追蹤更多 vocus 的最新精選內容從 Google News 追蹤更多 vocus 的最新精選內容

    你可能也想看

    發表回應

    成為會員 後即可發表留言
    © 2024 vocus All rights reserved.