匹配函数错误excel vba

嘿,我正在尝试使用或语句来执行一些条件,将决定是否将执行索引(匹配)属性的function。 但是,当myindex = 1的combobox(表单控件),它正确执行代码,但也给出了一个错误,说:“无法获得匹配属性..”可以有人帮助吗?

Option Explicit Dim ws As Sheets Dim i As Integer, j As Integer, p As Integer, q As Integer Dim myindex As Long, myitem As String Public Function FEC(i, j) Set ws = Sheets(Array("S1 Fuel Consumption", "EF_Stat", "Summary")) myindex = ws(1).Shapes("Fuel " & j).ControlFormat.Value If myindex = 2 Or 3 Or 4 Then With Application.WorksheetFunction FEC = .Index(ws(2).Range("B2:D5"), .Match(ws(1).Range("A" & i), ws(2).Range("A2:A5"), 0), .Match(ws(1).Shapes("Fuel " & j).ControlFormat.List(ws(1).Shapes("Fuel " & j).ControlFormat.ListIndex), ws(2).Range("B1:D1"), 0)) End With Else FEC = 0 End If End Function Sub Xecute() Set ws = Sheets(Array("S1 Fuel Consumption", "EF_Stat", "Summary")) For i = 7 To 15 Step 4 j = i - 6 Do While j < i - 2 ws(3).Range("D" & j).Value = FEC(i, j) j = j + 1 Loop Next i End Sub 

你的代码debugging起来非常复杂,因为在一行上有太多的事情发生。 我们无法确定哪个部分导致问题。 所以我build议你把它分解出来,这样你就可以看到发生了什么。

replace这个:

 With Application.WorksheetFunction FEC = .Index(ws(2).Range("B2:D5"), .Match(ws(1).Range("A" & i), ws(2).Range("A2:A5"), 0), .Match(ws(1).Shapes("Fuel " & j).ControlFormat.List(ws(1).Shapes("Fuel " & j).ControlFormat.ListIndex), ws(2).Range("B1:D1"), 0)) End With 

有了这个:

 With Application.WorksheetFunction Dim m1LookupValue As Variant Dim m2LookupValue As Variant Dim m1 As Variant Dim m2 As Variant m1LookupValue = ws(1).Range("A" & i) m2LookupValue = ws(1).Shapes("Fuel " & j).ControlFormat.List( _ ws(1).Shapes("Fuel " & j).ControlFormat.ListIndex) Debug.Print m1LookupValue Debug.Print m2LookupValue m1 = .Match(m1LookupValue, ws(2).Range("A2:A5"), 0) m2 = .Match(m2LookupValue, ws(2).Range("B1:D1"), 0) Debug.Print m1 Debug.Print m2 FEC = .Index(ws(2).Range("B2:D5"), m1, m2) End With 

现在你可以使用F8来遍历你的代码。 仔细查看查找值并确保它们在匹配函数的限制范围内。 然后仔细看m1和m2,确保它们在索引函数的限制范围内。

使用这种方法使得代码更容易阅读并且更容易debugging。 你仍然会得到这个错误,但现在你可以看到错误的确切位置。 希望你能自己解决。 如果没有,让我知道问题在哪里,variables的价值是什么。

也请务必做出Loannisbuild议的更改: myindex = 2 Or myindex = 3 Or myindex = 4