Excel VBA查找并返回符合多个条件的结果

时间:2016-12-12 15:05:31

标签: excel vba excel-vba matrix formula

所以我使用这个函数来查找单词出现的所有时间:

例如:

=BusquedaSimple(Sheet1!B1:B6; "*"&ESPACIOS(B1)&"*"; 1)

`sheet1`
    A       B       C
1 Basic    Case1   Return1
2 Basic6   Case1   Return2
3 Basic    Case1   Return3
4 Basic2   Case2   Return4
5 Basic    Case2   Return5
6 Basic5   Case3   Return6

`sheet2`
    A       B       C
1 Basic    Case1    =FUNCTION
2 Basic    Case2    =FUNCTION
3 Basic2   Case3    =FUNCTION

VBA功能:

Function BusquedaSimple(rng As Range, val As String, col As Long)
Application.ScreenUpdating = False
Dim i As Long, v, s
Dim r As Long

r = rng.Cells.count
v = Application.Match(val, rng, 0)
s = ""
Do While Not IsError(v)
    s = s & IIf(s <> "", Chr(10), "") & rng.Cells(v).Offset(0, col - 1).Value & ":" & rng.Cells(v).Offset(0, 0).Value
    r = r - v
    Set rng = rng.Offset(v, 0).Resize(r, 1)
    v = Application.Match(val, rng, 0)
Loop
BusquedaSimple = s
Application.ScreenUpdating = True
End Function

这很好,但是我知道,我需要匹配两个标准,例如:

=BusquedaSimple((Sheet1!B1:B6; "*"&ESPACIOS(B1)&"*"); (Sheet1!A1:A6; "*"&ESPACIOS(A1)&"*"); 1)

所以,我需要找到所有带有“ Case1 ”字符串的时间,但是,我需要确保该行也有一个像“ Basic < / em>“,并存储在一个单元格中(不是计数),但每个完整的字符串都已找到。

我怎么能做到这一点?

2 个答案:

答案 0 :(得分:0)

我不确定你想做什么,但我认为你可以轻松实现你想要的任何事情。使用VBA时,您不需要坚持使用工作表函数。我建议使用此函数来计算两个给定字符串的出现次数。然后,您可以开发更多内容以获得您想要的内容:

Function CountOccurrences(rng As Range, str1 As String, str2 As String) As Integer
    Dim cell As Range
   Dim count As Integer
   Dim WS As Worksheet

   Set WS = ActiveSheet
   count = 0

   For Each cell In rag
       If InStr(str1, cell.Value) > 0 And InStr(str2, cell.Value) > 0 Then
           count = count + 1
       End If
   Next cell

   CountOccurrences = count
End Function

答案 1 :(得分:0)

你能否使用原生公式,如COUNTIFS,或数组如下?

=SUM(--(LEFT(Sheet1!$A$2:$A$6,5)="Basic")*--(Sheet1!$B$2:$B$6="Case1"))+SUM(--(LEFT(Sheet2!$A$2:$A$6,5)="Basic")*--(Sheet2!$B$2:$B$6="Case1"))