我正在尝试索引和匹配2个单独列中的值。如果它是一个Excel公式,它将看起来像....
=INDEX('Critical Times'!D:D,MATCH(CONCATENATE(B7,C7),'Critical Times'!G:G,0))
我正在努力在VBA中执行此操作。我已经尝试了下面的代码,但无法正常工作。发生的情况是它沿着列的每一行向下移动,并为开始日期和结束日期写入一个值,直到它到达空白行为止。
我尝试了一个稍有不同的版本,其中仅将单元格C7与另一列匹配,并且工作正常。仅当我要加入B7和C7中的值时,它才停止工作。打扰一下,如果代码有点混乱,请继续学习!
Dim r As Range
Worksheets("Overview").Activate
Set r = Range("B7") & Range("c7")
Do While r.Value <> ""
Dim datestr As Long
Dim dateend As Long
datestr = WorksheetFunction.Index(Worksheets("Critical Times").Range("D:D"), WorksheetFunction.Match(r.Value, Worksheets("Critical Times").Range("G:G"), 0), 0)
dateend = WorksheetFunction.Index(Worksheets("Critical Times").Range("E:E"), WorksheetFunction.Match(r.Value, Worksheets("Critical Times").Range("G:G"), 0), 0)
Dim MatchFormula As Long
Dim ColumnMatch As Long
Dim MatchFormula2 As Long
Dim ColumnMatch2 As Long
If datestr <> 0 Then
MatchFormula = WorksheetFunction.Match(r.Value, Range("C:C"), 0)
ColumnMatch = WorksheetFunction.Match(datestr, Range("4:4"), 0)
Range(Col_Letter(ColumnMatch) & MatchFormula).Value = "A"
MatchFormula2 = WorksheetFunction.Match(r.Value, Range("C:C"), 0)
ColumnMatch2 = WorksheetFunction.Match(dateend, Range("4:4"), 0)
Range(Col_Letter(ColumnMatch2) & MatchFormula2).Value = "A"
End If
Set r = r.Offset(1)
Loop
答案 0 :(得分:0)
让我们想象一下这个示例数据:
| Tests | Vals | Return |
|-------|------|--------|
| Test1 | Val1 | Ret1 |
| Test1 | Val2 | Ret2 |
| Test1 | Val3 | Ret3 |
| Test1 | Val4 | Ret4 |
| Test1 | Val5 | Ret5 |
| Test2 | Val1 | Ret6 |
| Test2 | Val2 | Ret7 |
| Test2 | Val3 | Ret8 |
| Test2 | Val4 | Ret9 |
| Test2 | Val5 | Ret10 |
| Test3 | Val1 | Ret11 |
| Test3 | Val2 | Ret12 |
| Test3 | Val3 | Ret13 |
| Test3 | Val4 | Ret14 |
| Test3 | Val5 | Ret15 |
要基于多个条件(在这种情况下为col A和col B)返回某个值,我们可以在如下范围内使用一些迭代:
Sub Test()
Dim rng As Range, cl As Range
Dim var1 As String, var2 As String, fa As String
var1 = "Test2"
var2 = "Val4"
With Worksheets("Sheet1")
Set rng = .Range("A2:A" & .Cells(.Rows.Count, "A").End(xlUp).Row)
For Each cl In rng
If cl.Value = var1 And cl.Offset(0, 1).Offset = var2 Then
Debug.Print cl.Offset(0, 2).Value
Exit For
End If
Next cl
End With
End Sub
如果您的数据范围很大,那么研究.FindNext
可能会有所益处,以防止较长的迭代和处理时间。
如果确定这些值存在,则还可以使用.Evaluate
函数来模拟工作表函数并返回其结果。在这种情况下,.Evaluate
会识别出您打算使用数组公式,因此不需要第二个INDEX
。示例:
Sub Test2()
Dim rng As Range, cl As Range
Dim var1 As String, var2 As String, fa As String
var1 = "Test2"
var2 = "Val4"
With Worksheets("Sheet1")
Debug.Print .Evaluate("=INDEX(C:C,MATCH(1,(A:A=""" & var1 & """)*(B:B=""" & var2 & """),0))")
End With
End Sub
要缩短处理时间,您可以定义范围并在评估公式中实现这些范围。