COUNTIFS函数可跨多个工作表

问题描述 投票:0回答:1

enter image description here

如何将vlookup包含在当前代码集中,以便对所有相似工作表中的所有vlookup结果进行计数。我将执行的代码将尝试跨列或行中的一个指定的单元格整个数据范围的工作表执行计数。相反,我希望下面的函数能够对相似名称的工作表中的列中的vlookup结果数量进行计数。

Function myCountIfSheet1(rng As Range, criteria) As Long
    Dim ws As Worksheet

    For Each ws In ThisWorkbook.Worksheets
        If ws.Name Like "Sheet1*" Then
            myCountIfSheet1 = myCountIfSheet1 + WorksheetFunction.CountIf(ws.Range(rng.Address), criteria)
        End If
    Next ws
End Function



Public Function shifted_lookup(lookup_value As Variant, table_array As Range, column_index As Integer, range_lookup As Integer) As Variant
    Dim curr_wsname As String, oth_wsname As String
    Dim curr_ws As Worksheet, oth_ws As Worksheet
    Set curr_ws = ActiveSheet
    curr_wsname = curr_ws.Name
    oth_wsname = Right(curr_wsname, 3)
    Set oth_ws = Worksheets(oth_wsname)
    Dim src_rng_base As String, src_rng As Range
    src_rng_base = table_array.Address
    Set src_rng = oth_ws.Range(src_rng_base)
    Dim aux As Variant
    shifted_lookup = Application.WorksheetFunction.VLookup(lookup_value, src_rng, column_index, range_lookup)
End Function
excel vba vlookup countif
1个回答
1
投票

这应该完成工作。请尝试。

Function myCountIfSheet1(Rng As Range, _
                         Clm1 As Long, _
                         Crit1 As Variant, _
                         Clm2 As Long, _
                         Crit2 As Variant) As Long

    Dim Fun As Long                         ' function return value
    Dim Ws As Worksheet

    For Each Ws In ThisWorkbook.Worksheets
        With Ws
            If .Name Like "Sheet1*" Then
                Fun = Fun + WorksheetFunction.CountIfs( _
                            .Range(Rng.Columns(Clm1).Address), Crit1, _
                            .Range(Rng.Columns(Clm2).Address), Crit2)
            End If
        End With
    Next Ws

    myCountIfSheet1 = Fun
End Function

为了便于调用,我已将函数调用结构化为仅提供一个范围地址。在测试中,我使用了A1:D30。栏(A)包含一个条件,栏(D)包含另一个条件。当然,列(A)是范围的第一列-列(1)-列D是范围的列(4)。因此,以下函数调用将在A列中查找“ 3”,在D列中查找“红色”。

Debug.Print myCountIfSheet1(Range("A1:D30"), 4, "red", 1, 3)

标准的顺序无关紧要。您也可以使用相同的结构添加更多条件。

© www.soinside.com 2019 - 2024. All rights reserved.