首页 > 解决方案 > 索引匹配函数:迭代多个条件

问题描述

对不起,我最初的帖子没有提供我想要做什么的详细描述。

我想在匹配两个条件时获取单元格的值。一个标准是固定单元格,而第二个标准是我需要对其进行迭代。

例子:

Cells(2,1) = A(它与“名称”和 匹配Criteria2 (Cells(1,6)),因为Cells(3,1)我想应用相同的名称,但使用Criteria2 (Cells(2,6))等等。

我的替代方法是过滤 Range Criteria 1(我已经这样做了),然后获取所有可用的值,但是我必须对 3 个不同的集合应用相同的过程,我觉得我可以使用 match/Index 有更好的方法.

您可以在下面找到我的 excel 文件、代码和输出。

在此处输入图像描述

这是我的代码的输出:

在此处输入图像描述

这是我的代码:

Sub match_index()

Dim ws As Worksheet
Set ws = Worksheets("Sheet1")

Dim i As Long
i = 2

Dim criteria1 As String
criteria1 = ws.Cells(1, 4).Value
Dim criteria2 As String
criteria2 = ws.Cells(1, 6).Value

Dim criteria_range1 As Range
Set criteria_range1 = ws.Range(ws.Cells(2, 8), ws.Cells(14, 8))
Dim criteria_range2 As Range
Set criteria_range2 = ws.Range(ws.Cells(2, 9), ws.Cells(14, 9))


With Application
While i < 8
        ws.Cells(i, 1).Value = .Index(criteria_range2, _
        .Match(criteria1, criteria_range1, 0), _
        .Match(ws.Cells(i, 6).Value, criteria_range2, 0), 1)
        i = i + 1
Wend
End With

End Sub

标签: excelvba

解决方案


我设法找到了解决方案。我将 If 语句与 Like 函数一起使用:

x = 2
y = 1
For i = 2 To 14
    criteria2 = ws.Cells(y, 6).Value
    If criteria1 Like ws.Cells(i, 8).Value And criteria2 Like ws.Cells(i, 9).Value Then
        ws.Cells(x, 1).Value = ws.Cells(i, 9).Value
        y = y + 1
        x = x + 1
    End If
    Next i
End Sub

推荐阅读