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 Next Next
Cells(47, …does not refer to the same sheet as
Sheet7.Rangeyou must specify a worksheet for every
Cellsobject too. Like:
WorksheetFunction.Matchwill throw an error if nothing mached. So you need to catch that case and decide what to do in case nothing matches.
I recommend always to activate
Option Explicit: In the VBA editor go to Tools › Options › Require Variable Declaration and declare all your variables properly.
Numbered variable names like
Count_2are pretty shitty, because the get mixed up quickly. Instead always use meaningful variable names like
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 NO_MATCH: MsgBox "The value '" & Sheet8.Cells(iRow, 1).Value & "' was not found in Range A47:A904. Aborting." Exit Sub NO_INDEX: MsgBox "Index failed at cell(" & iRow & ", " & iColumn & "). Aborting." End Sub