Home » excel » excel – Getting Application Defined or User Defined Error

excel – Getting Application Defined or User Defined Error

Posted by: admin May 14, 2020 Leave a comment


I am racking my brain to figure out why i get an Error 1004 on this. I have a worksheet with unique identifiers that I need to find in another worksheet then return a value in a different column on the row and it seemed WorksheetFunction.Index+Match. The data I need is offset by one column (hence the Count_2 – 1). I have declared the variables and even unlocked the sheets just in case. I know I could use index match within excel but I am trying to use vba for all calculations so that end users can’t mess anything up and so that it will be easier to see what the workbook is actually doing. Any ideas?

Separately I have been setting it to print out a number to a specific cell so I can more easily see where the code is dying.

For Count_1 = 2 to 51

    For Count_2 = 4 To 44

        Sheet8.Cells(Count_1, Count_2) = WorksheetFunction.Index(Sheet7.Range(Cells(47, Count_2 -1), _
        Cells(904, Count_2 - 1)), WorksheetFunction.Match(Sheet8.Cells(Count_1, 1).Value, _
        Sheet7.Range("A47:A904"), 0))

        Count_3 = Count_3 + 1
        Sheet1.Range("D1") = 2


How to&Answers:
  1. Cells(47, … does not refer to the same sheet as Sheet7.Range you must specify a worksheet for every Cells object too. Like: …Sheet7.Range(Sheet7.Cells(47, …

  2. WorksheetFunction.Match will throw an error if nothing mached. So you need to catch that case and decide what to do in case nothing matches.

  3. I recommend always to activate Option Explicit: In the VBA editor go to ToolsOptionsRequire Variable Declaration and declare all your variables properly.

  4. Numbered variable names like Count_1 and Count_2 are pretty shitty, because the get mixed up quickly. Instead always use meaningful variable names like iRow and iColumn.

So you will end up with something like:

Option Explicit

Public Sub Example()
    Dim CellsProcedured As Long

    Dim iRow As Long
    For iRow = 2 To 51

        Dim iColumn As Long
        For iColumn = 4 To 44

            Dim MatchResult As Double
            On Error GoTo NO_MATCH
            MatchResult = Application.WorksheetFunction.Match(Sheet8.Cells(iRow, 1).Value, Sheet7.Range("A47:A904"), 0)
            On Error GoTo 0

            On Error GoTo NO_INDEX
            Sheet8.Cells(iRow, iColumn) = Application.WorksheetFunction.Index(Sheet7.Range(Sheet7.Cells(47, iColumn - 1), Sheet7.Cells(904, iColumn - 1)), MatchResult)
            On Error GoTo 0

            CellsProcedured = CellsProcedured + 1
            Sheet1.Range("D1") = 2

        Next iColumn
    Next iRow

    Exit Sub

    MsgBox "The value '" & Sheet8.Cells(iRow, 1).Value & "' was not found in Range A47:A904. Aborting."

    Exit Sub

    MsgBox "Index failed at cell(" & iRow & ", " & iColumn & "). Aborting."
End Sub