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

时间:2018-12-13 10:33:16

标签: excel vba runtime-error userform worksheet

我将在VBA模块中运行良好的代码复制到了UserForm,因为我需要组合一些在userform中定义的动作。现在我在执行以下部分时陷入困境,出现错误消息“应用程序定义的错误或对象定义的错误”

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

尽管很多人都遇到过同样的问题,但我找不到适合我的解决方案。有提示吗?

非常感谢!

1 个答案:

答案 0 :(得分:1)

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

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

变成工作代码:
?thisworkbook.Worksheets("Ref").cells(2,"7")返回您的错误。
?thisworkbook.Worksheets("Ref").cells(2,7)返回范围G2中的值。


话虽如此,我想我能明白你的追求:
A工作表的第Ref列中填充了数字,您想在该列中搜索特定的数字,如果找到该数字,则返回GH列中的值在那排。

此代码将在包含代码(1)的工作簿中名为A的工作表Ref的列ThisWorkbook中找到数值G:H。然后它将从该行的列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 返回值,或者将返回一个空字符串。

val = dict()
def vote(val,person):
    if person not in val:
        val[person] = 1
    else:
       val[person] = val[person] + 1

def votes(val,person):
    if person in val:
        print val[person]

def result(val):
    ex = sorted(val.items(), key = lambda val:val[1], reverse=True)
    if len(ex) == 0:
        print '***NONE***'
    #Problem below
    elif ex[0] == ex[1]:
        print '***NONE***'
    else:
        print ex[0][0]   
Output: 
>>>vote(val,'Peter')
>>>vote(val,'Peter')
>>>votes(val,'Peter')
2
>>>vote(val,'Lisa')
>>>vote(val,'Lisa')
>>>votes(val,'Lisa')
2
>>>result(val)
Lisa
>>> print val
{'Lisa': 2, 'Peter': 2}