excel - 为什么对象不支持这种方法?

标签 excel vba properties

我有以下代码

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
enter image description here
这就是我的excel的样子
该代码一开始可以工作,但是在我更改了一些值后,它突然不工作了,并且弹出了上述错误。
有人能告诉我为什么吗?非常感谢你的帮助

最佳答案

Application.Match对比 WorksheetFunction.Match (WorksheetFunction.Index)

  • 你拼错了WorksheetFunction在您提到的代码中
    Raymond Wu 评论:Worksheet.Match应该是 WorksheetFunction.Match .
  • 早绑定(bind)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/

    相关文章:

    excel - 在语句 VBA 中使用多个喜欢

    java - 如何对读取属性文件的类进行单元测试

    c# - 操纵 setter 以避免 null

    vba - 使用 LINEST 5000 次执行梯度计算,无需手动输入代码

    python - 使用 python 自动化 Excel 宏

    c# - 在 C# 中将 OracleDataReader 导出到 Excel

    vba - 使用 Excel 2016 将范围保存为图片

    excel - 每次循环后将信息写入 Excel

    vba - Excel:选择所有行直到空单元格

    c++ - 自定义类型的 Qml 属性