匹配不工作Excel:错误1004无法获取匹配属性

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 

我只想在三个不同的variables上获取用户的stringinput,并find包含每个variables的列。 我已经尝试过Application.Match()和Match(),而且都没有工作。

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 ,只有strCountStringtypes,但strMake, strModelVariant

Dim makeLoc, modelLoc, countLoc As Integer – 只有countLoc具有Integertypes。

没有完整的技术,不会发布代码。 但是,有三件事情:

,确保你的范围总是完全合格的。 例如, Range("A1:A10")还远远不够。 您应该指定应在哪张纸上。 如果您从另一个工作表调用此macros,它会给你一个错误的结果或抛出一个错误。

,没有太多的细节:

  1. 如果找不到匹配, Application.Match将返回错误值。 这可以使用IsError来处理,这是simoco在他的答案中所做的。
  2. WorksheetFunction.Match没有发现错误时会抛出 1004错误。 这不像返回一个值。 因此,这是(稍微)更难处理。

最佳做法是始终使用第一个。

,VBE的直接窗口是你最好的朋友。 窗口中的一个简单的?Application.Match("FindMe", [A1:A10], 0)可以帮助您检查您的公式是否获得了类似的预期结果。

Application.Match返回一个错误值

如上面的截图所示,没有findstring,并返回一个错误值。

希望这可以帮助!