VBA 用户窗体:应用程序定义或对象定义的错误

VBA userform: application-defined or object-defined error

我将 VBA 模块中运行良好的代码复制到用户窗体,因为我需要组合用户窗体中定义的一些操作。现在我在执行以下部分时卡住了,错误消息 'Application-defined or object-defined error'

Sub test()
    Dim Myworkbook As workbook
    Dim Myid As Variant

    Set Myworkbook = ThisWorkbook

    Myid=1

    Myref=FinRef(Myworkbook, "Ref", Myid)
End Sub

    Function FinRef(myfile As Workbook, InputSheet As String, Ref_ID As Variant) 

        Dim I, k, LinkFrom, Description As Integer
        Dim Linkdescrip As String

        FinRef = ""

        LinkFrom = 1           
        Description = 8             
        Linkdescrip = 7             
        For I = 2 To 3000
            k = myfile.Sheets(InputSheet).Cells(I, LinkFrom)

            If k = Ref_ID Then
                FinRef = FinRef & myfile.Sheets(InputSheet).Cells(I, Linkdescrip) & myfile.Sheets(InputSheet).Cells(I, Description)
            End If
        Next I

    End Function

虽然有很多人遇到同样的问题,但我找不到适合我的解决方案。有什么建议吗?

非常感谢!

正如约翰所说 - 您发布的代码不会产生您报告的错误。

我认为您的代码存在问题:
Dim Linkdescrip As String 应该是 Dim Linkdescrip As Long

转换为工作代码:
?thisworkbook.Worksheets("Ref").cells(2,"7") return你的错误。
?thisworkbook.Worksheets("Ref").cells(2,7) returns 范围 G2.

中的值

话虽如此,我想我能看出你在追求什么:
Ref sheet 的第 A 列填充了数字,您想在该列中搜索特定数字,如果找到,则查找 return 列 [=18] 中的值=] & H 在该行。

此代码将在包含代码 (ThisWorkbook ).然后它将 return 来自该行的列 G:H 的值,或者它将 return 一个空字符串。

Sub Test()

    Dim MyRef As String

    MyRef = FinRef(ThisWorkbook.Worksheets("Ref"), 1)

End Sub

Public Function FinRef(InputSheet As Worksheet, Ref_ID As Long) As String

    Dim rFound As Range

    With InputSheet
        Set rFound = .Columns(1).Find( _
            What:=Ref_ID, After:=.Cells(1, 1), _
            LookIn:=xlValues, LookAt:=xlWhole, _
            SearchOrder:=xlByRows, SearchDirection:=xlNext)

        If Not rFound Is Nothing Then
            FinRef = rFound.Offset(, 6) & rFound.Offset(, 7)
        End If

    End With

End Function