I want to loop through rows and columns in VBA.
I have a table of recipes for ceramic glazes:
![[image of db]](https://www.lemona.fr/i.sstatic.net/7jrE1.png)
Not all recipes have the same amount of ingredients.
These recipes aren't real.
I want to generate a list of recipes with the title of the recipe followed by the ingredients and the amount of each ingredient:
![[image with sample recipes]](https://www.lemona.fr/i.sstatic.net/vTVnj.png)
I modified a code snippet found here:
Sub ExtractRecipes()
Dim wsSrc As Worksheet: Set wsSrc = Worksheets("cone6")
Dim wsDest As Worksheet: Set wsDest = Worksheets("output")
Dim LastRow As Long: LastRow = wsSrc.UsedRange.Find("*", SearchOrder:=xlByRows, SearchDirection:=xlPrevious).row
Dim LastCol As Long: LastCol = wsSrc.UsedRange.Find("*", SearchOrder:=xlByColumns, SearchDirection:=xlPrevious).Column
Dim i As Long, j As Long, RowCounter As Long: RowCounter = 1
On Error Resume Next
With wsDest
For i = 1 To LastRow
.Cells(RowCounter, 1) = wsSrc.ListObjects("testTable").ListColumns("recipe").DataBodyRange.Cells(i)
For j = 1 To LastCol
If wsSrc.ListObjects("testTable").DataBodyRange.Cells(i, j) <> "" Then
.Cells(RowCounter + 1, 1) = wsSrc.ListObjects("testTable").ListColumns("material_" & j).DataBodyRange.Cells(i)
.Cells(RowCounter + 1, 2) = wsSrc.ListObjects("testTable").ListColumns("material_amount_" & j).DataBodyRange.Cells(i)
.Cells(RowCounter + 1, 3) = Err.Description
RowCounter = RowCounter + 1
End If
Next j
Next i
End With
End Sub
I get an error
subscript out of range
![[output]](https://www.lemona.fr/i.sstatic.net/cHxfw.png)
On Error Resume Nextand see what line is failing. At a guess it's thejvariable goes to 8 but your labeling scheme goes to 4, so there is no material_7 for instance..Cells(RowCounter + 1, 1) = wsSrc.ListObjects("testTable").ListColumns("material_" & j).DataBodyRange.Cells(i)