我正在尝试使用索引和匹配工作表函数将项目编号从用户表单中的组合框(ItemNum.value)与工作表上的产品列表表(“产品定价”)相匹配。然后拉出与该工作表中相同行匹配的单元格(“产品定价”),并将它们复制到输入数据工作表上的单元格(“i4”)(“查看照明数据”)。问题是我每次运行宏时都会给出错误“1004无法获取WorksheetFunction类错误的匹配属性”
我的代码是:
Private Sub InputLight_Click()
With Sheets("Review Lighting Data")
.Range("i4").Value = Application.WorksheetFunction.Index(Sheets("Product Pricing").Range("c7:c102"), Application.WorksheetFunction.Match(ItemNum.Value, Sheets("Product Pricing").Range("b7:b102"), 0))
End With
End Sub
我已经尝试开始使用新工作簿来尝试简化操作。到目前为止,这是我的完整代码:
Private Sub inputbutton_Click()
Dim MatchRow As Long
Dim WS0 As Worksheet, WS1 As Worksheet
Dim R0 As Range, R1 As Range
With ThisWorkbook
Set WS0 = .Sheets("Review Lighting Data")
Set WS1 = .Sheets("Product Pricing")
End With
With WS1
Set R0 = WS1.Range("B7:B11")
Set R1 = WS1.Range("C7:C11")
End With
MatchRow = Application.Match(itemnum.Value, R0, 0)
MsgBox MatchRow
End Sub
Private Sub UserForm_Initialize()
With Me.itemnum
.AddItem "1001"
.AddItem "1002"
.AddItem "1003"
.AddItem "1004"
.AddItem "1005"
End With
End Sub
我已将项目编号输入组合框(itemnum),没有任何空格或任何内容。我甚至尝试删除“每个数字周围的标记,但这也不起作用。我已经尝试输出(MatchRow)到MsgBox中以尝试捕获错误但它在它之前中断。
答案 0 :(得分:1)
问题是当Match
未在范围内找到值时,它会返回错误。您可以使用IsError
:
Private Sub InputLight_Click()
Dim matchRes
With Sheets("Review Lighting Data")
matchRes = Application.Match(ItemNum.Value, Sheets("Product Pricing").Range("b7:b102"), 0)
If Not IsError(matchRes) Then
.Range("i4").Value = Application.Index(Sheets("Product Pricing").Range("c7:c102"), matchRes)
End If
End With
End Sub
答案 1 :(得分:1)
一个好的做法是正确地确定一切。这使代码更易于阅读和调试。此外,您必须使用Application.Match
而不是Application.WorksheetFunction...
。
Private Sub InputLight_Click()
Dim MatchRow
Dim WS0 As Worksheet, WS1 As Worksheet
Dim R0 As Range, R1 As Range
With ThisWorkbook
Set WS0 = .Sheets("Review Lighting Data")
Set WS1 = .Sheets("Product Pricing")
End With
With WS1
Set R0 = .Range("B7:B102")
Set R1 = .Range("C7:C102")
End With
MatchRow = Application.Match(ItemNum.Value, R0, 0)
If Not IsError(MatchRow) Then
WS0.Range("I4").Value = Application.Index(R1, MatchRow)
End If
End Sub
这里有一个非常类似的问题:Match Not working Excel: Error 1004 Unable to get the Match Property,其中@simoco和我也同样处理过它。
答案 2 :(得分:0)
好了,尝试了一系列不同的方法让匹配索引在userform中工作后,我决定“欺骗”一点,并且只是在单元格中使用常规匹配索引函数。非常感谢你的帮助!