Search code examples
vbaexcel-365

How to paste data into a specific row based on cell value?


I have a database worksheet. Every month we receive multiple plannings from factories, which I paste into a workbook from where I do analyses. But I want to automate.

For your reference I pasted an (adjusted) snippet of the workbook below:

[![workbook][1]][1]

In column B the month of data entry is listed. The line below works to filter on the current month:

Worksheets("Production Plan Input").Range("A1:BQ290").AutoFilter Field:=2, Criteria1:=xlFilterThisMonth, Operator:=xlFilterDynamic

But now I want to match the product group in column C of the filtered range to the workbooks with the different plannings.

For this, I need to copy range B3:Y3 from Workbook "Product type 1" worksheet "Monthly Plan" into workbook "Production Plan Analysis", worksheet "Plan Input", column AD:BA, but the row depends on the product type.


    Dim lastRow As Long
    Dim ws As Worksheet
    Dim i As Long

ws = ThisWorkbook.Sheets("Production Plan Input")

lastRow = ws.Cells(ws.Rows.Count, "C").End(xlUp).Row
    For i = 1 To lastRow
    If ws.Cells(i, "C").Value = "exe" Then
    ws.Range("AD" & i & ":BA" & i).Value = Paste
    End If
    

I get the error message "Compile Error: for without Next"


Solution

  • To get rid of the error:

    enter image description here

    After got rid of the compile time error, there is another error, now a runtime error, because you are not setting ws variable.
    Just correct your piece of code:

     Public Sub Test()
        Dim lastRow As Long
        Dim ws As Worksheet
        Dim i As Long
    
        Set ws = ThisWorkbook.Sheets("Production Plan Input")
        '^^^^ Another error that you would catch after pass the missing Next error
        lastRow = ws.Cells(ws.Rows.Count, "C").End(xlUp).Row
        For i = 1 To lastRow
            If ws.Cells(i, "C").Value = "exe" Then
                ws.Range("AD" & i & ":BA" & i).Value = Paste
            End If
        Next ' <= here what is missing
    End Sub