Troubleshooting Error 1004: Application-Defined or Object-Defined Error

zxpoghnqklqn
Community Visitor

Troubleshooting Error 1004: Application-Defined or Object-Defined Error

zxpoghnqklqn
Community Visitor
Community Visitor

Hi, My Name is Alexa, and I work for Piping Project as a Steel Plate Manufacturer in USA in the company. I'm encountering an error message "Run-time error '1004': Application-defined or object-defined error" in my VBA code. I'm not sure what's causing it, and it's not providing much context. Can someone help me understand what might be causing this and how to resolve it?

0 Likes
Reply
400 Views
1 Reply
Reply (1)

ed57gmc
Mentor
Mentor

You apparently do not have any structured error handling in your code. A compile error will be flagged by the compiler, but a runtime error will not. If you have SubA that calls SubB, and SubB has a runtime error that is not handled, then it will bubble up to SubA and you may think that SubA was the cause of the error. Without any error handling, the best you can narrow it down to in troubleshooting, is that the problem was in the last command you ran. Below is a function that I've added error handling to. If an error occurs, code execution is routed to Err_Control. Here the error code is tested against possible known errors using a Select..Case statement. If a Case tests true, you can handle the error, reset the error object and resume at Exit_Here or some other point in the sub. If none of the errors test true, execution flows to the Case..Else statement, which just reports the error and the dialog title gives you the function that errored. Then you can set a breakpoint in the function/sub and continue debugging.

Public Function XYZDistance(Point1 As Variant, Point2 As Variant) As Double
    On Error GoTo Err_Control
    'Returns the distance between two points
    Dim dblDist As Double
    Dim dblXSl As Double
    Dim dblYSl As Double
    Dim dblZSl As Double
    Dim varErr As Variant
    On Error GoTo Err_Control
    'Calc distance
    dblXSl = (Point1(0) - Point2(0)) ^ 2
    dblYSl = (Point1(1) - Point2(1)) ^ 2
    dblZSl = (Point1(2) - Point2(2)) ^ 2
    dblDist = Sqr(dblXSl + dblYSl + dblZSl)
    'Return Distance
    XYZDistance = dblDist
Exit_Here:
    Exit Function
Err_Control:
    Select Case Err.Number
    'Add your Case selections here
    'Case Is = 1000
        'Handle error
        'Err.Clear
        'Resume Exit_Here
    Case Else
        MsgBox Err.Number & ", " & Err.Description, , "XYZDistance"
        Err.Clear
        Resume Exit_Here
    End Select
End Function

 

Ed


Did you find this post helpful? Feel free to Like this post.
Did your question get successfully answered? Then click on the ACCEPT SOLUTION button.
How to post your code.

EESignature

0 Likes