我有以下代码
Dim Shop1 As String
With Worksheets("Data Page")
Shop1 = Application.WorksheetFunction.Index(.Range("B2:B7"), Application.Worksheet.Match(profitable1, .Range("E2:E7"), 0))
End With
这就是我的excel的样子
该代码一开始可以工作,但是在我更改了一些值后,它突然不工作了,并且弹出了上述错误。
有人能告诉我为什么吗?非常感谢你的帮助
最佳答案
Application.Match
对比 WorksheetFunction.Match
(WorksheetFunction.Index
)
WorksheetFunction
在您提到的代码中Raymond Wu 评论:
Worksheet.Match
应该是 WorksheetFunction.Match
. WorksheetFunction
Match
的版本如果找不到值,将引发错误,因此您必须实现某种错误处理。后期绑定(bind)Application
首选版本,因为它可以使用 IsNumeric
进行测试或 IsError
. Index/Match
在 VBA 中。它通常按照以下代码所示进行处理。 Option Explicit
Sub Test()
Dim sIndex As Variant ' a number or an error value, hence 'As Variant'
Dim profitable1 ' ?
Dim Shop1 As String ' this actually means Shop1 = ""
With ThisWorkbook.Worksheets("Data Page")
With .Range("E2:E7")
sIndex = Application.Match(profitable1, .Cells, 0)
If IsNumeric(sIndex) Then
Shop1 = CStr(.Cells(sIndex).EntireRow.Columns("B").Value)
' Or:
'Shop1 = CStr(.Cells(sIndex).Offset(, -3).Value)
'Else ' if the code is in a loop
' Shop1 = ""
End If
End With
End With
End Sub
Sub Test2()
Dim sIndex As Variant ' a number or an error value, hence 'As Variant'
Dim profitable1 ' ?
Dim Shop1 As String ' this actually means Shop1 = ""
Dim lrg As Range ' Lookup
Dim vrg As Range ' Value
With ThisWorkbook.Worksheets("Data Page")
Set lrg = .Range("E2:E7")
Set vrg = .Range("B2:B7")
End With
sIndex = Application.Match(profitable1, lrg, 0)
If IsNumeric(sIndex) Then
Shop1 = CStr(vrg.Cells(sIndex).Value)
'Else ' if the code is in a loop
' Shop1 = ""
End If
End Sub
关于excel - 为什么对象不支持这种方法?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71731415/