Home > Net >  Add a constant value to a cell on each iteration
Add a constant value to a cell on each iteration

Time:07-25

How can I add a fixed value (2 in this case) to a cell on each iteration?

I need to automatize the value of two cells (C1 and C2) to generate a receipt and print it. The range is from 1 to 550 and the model has two receipts on it (1 and 2, 3 and 4...).

There is what i'm trying to do:

Sub print_pdf()

first = Range("R1").Value
'That is 1

last = Range("R2").Value
'That is 550

For i = first To last
            Range("C1").FormulaR1C1 = i
            Range("C2").FormulaR1C1 = i   1
            
                file_name = Range("C1") & "-" & Range("C2") & ".pdf"
                ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=file_name

Next
Range("C1") = ""
Range("C2") = ""

End Sub



CodePudding user response:

Use Step 2 in for loop. Give a try on below sub-

Sub print_pdf()
    first = Range("R1").Value
    'That is 1
    
    last = Range("R2").Value
    'That is 550
    
        For i = first To last Step 2
            Range("C1").FormulaR1C1 = i
            Range("C2").FormulaR1C1 = i   1
            Debug.Print i & "-" & i   1
                'file_name = Range("C1") & "-" & Range("C2") & ".pdf"
                'ActiveSheet.ExportAsFixedFormat Type:=xlTypePDF, Filename:=file_name
        Next
    Range("C1") = ""
    Range("C2") = ""
End Sub

Actually do not need to store file name in cell like C1, C2. Instead you can use variable directly to make a file name like-

file_name = i & "-" & i   1 & ".pdf"
  • Related