![](/img/trans.png)
[英]Excel VBA: unable to get the match property of the worksheetfunction class Run-time error 1004
[英]Match Not working Excel: Error 1004 Unable to get the Match Property
Sub Sales_Summary_Macro()
Dim strMake, strModel, strCount As String
Dim makeLoc, modelLoc, countLoc As Integer
strMake = Application.InputBox("Make")
strModel = Application.InputBox("Model")
strCount = Application.InputBox("Count")
If strMake <> False Then
Debug.Print strMake
Debug.Print strModel
Debug.Print strCount
makeLoc = WorksheetFunction.Match(strMake, Range("A1:A10"), 0)
Debug.Print makeLoc
End If
End Sub
我只想在三個不同的變量上獲取用戶的字符串輸入,並找到包含每個變量的列。 我已經嘗試過Application.Match()和Match(),但似乎都沒有用。
不完全技術,不會發布代碼。 但是,有三件事:
第一 ,請確保您的范圍始終完全合格。 例如, Range("A1:A10")
還不夠。 您應指定此文件應位於哪張紙上。 如果您從另一個工作表調用此宏,它將給您錯誤的結果或引發錯誤。
二 ,沒有太多細節:
Application.Match
將返回錯誤值。 這可以使用IsError
來處理,這是simoco在他的回答中所做的。 WorksheetFunction.Match
在找不到錯誤時拋出 1004
錯誤。 這與返回值不同。 因此,這(稍微)難以處理。 最佳做法是始終使用第一個。
三 ,VBE的直接窗口是你最好的朋友。 窗口中的簡單?Application.Match("FindMe", [A1:A10], 0)
可以幫助您檢查公式是否得出相似的預期結果。
如上面的屏幕截圖所示,未找到任何字符串並返回錯誤值。
希望這可以幫助!
UPD:
是否有可能讓它像C1一樣返回單元格引用,然后在其他函數中使用該單元格引用
Sub Sales_Summary_Macro()
Dim strMake As String, strModel As String, strCount As String
Dim makeLoc, modelLoc As Integer, countLoc As Integer
Dim res As Range
strMake = Application.InputBox("Make")
strModel = Application.InputBox("Model")
strCount = Application.InputBox("Count")
If strMake <> "False" Then
Debug.Print strMake
Debug.Print strModel
Debug.Print strCount
On Error Resume Next
'Set res = Range("A1:Z1").Find(What:=strMake, LookAt:=xlWhole, MatchCase:=False)
Set res = Application.Index(Range("A1:A10"), Application.Match(strMake, Range("A1:A10"), 0))
On Error GoTo 0
If res Is Nothing Then
MsgBox "Nothing found!"
Exit Sub
End If
'Print address of result
Debug.Print res.Address
makeLoc = res.Value
Debug.Print makeLoc
End If
End Sub
順便說一句,
當你使用Dim strMake, strModel, strCount As String
,只有strCount
有String
類型,但是strMake, strModel
是Variant
。
與Dim makeLoc, modelLoc, countLoc As Integer
- 只有countLoc
具有Integer
類型。
這不是一個直接的答案給OP,而是試圖用TRAP VBA一個錯誤,當人(像我)可能會發現這個問題有幫助的Match
。 通常,我將使用它來測試數組中是否存在值。
使用Application.Worksheetfunction.Match
時非常發瘋, IsError
當不存在值時無法使用IsError
捕獲True
。 甚至WorksheetFunction
錯誤處理程序( iserr
, isNA
等)也不會將其捕獲為True
,而是拋出VBA錯誤1004 Unable to get Match Property 。
這是通過使用解決Application.Match
代替Application.WorksheetFunction.Match
。 這是違反直覺的,因為在輸入Application.
后Match
不會出現在intellisense中Application.
Application.Match(
也不顯示輸入哪些字段的提示。
同時使用Application.WorksheetFunction.Match
會自動填充提示,這些提示可以激發用戶采用這種方法,然后混淆為什么他們無法成功捕獲錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.