You are here:

Excel/repeat formula vba


Hello Tom,

I am writing the following code in a worksheet (excel 2003).

I need to repeat this code for 68 rows down. I am hoping that I down't have to type the code over 68 times changing the row numbers each time. Is there a solution in VBA?

X2 is a constant range to check, then row number down for column "C" and "N". If I have to do this manually, I will have 68 end if statements.

Thank you

Dim wsP As Worksheet
Set wsP = ThisWorkbook.Sheets("Permission")
If wsP.Range("N4") = 0 Then
wsP.Range("C4") = wsP.Range("X2")
If wsP.Range("N5") = 0 Then
wsP.Range("C5") = wsP.Range("X2")
End If
End If
End Sub


I would approach it this way (if I properly understand what you are trying to do)

Make a copy of your workworkbook/worksheet and run the macro on the copy until you are sure it is doing what you want.

Dim wsP As Worksheet, cell as Range
Set wsP = ThisWorkbook.Sheets("Permission")
' loop down column N starting in row 4
for each cell in wsp.Range("N4").Resize(68,1)
If cell  = 0 Then
  ' set column C of that row to the value in cell X2
  wsP.Cells(cell.row, "C").value = wsP.Range("X2").value
End If
Next cell
End Sub

Tom Ogilvy  
About Excel
This topic answers questions related to Microsoft Excel spreadsheet (or workbook) stand-alone or Mircrosoft Office Excel including Excel 2003, Excel 2007, Office 2000, and Office XP. You can get Excel help on Excel formulas(or functions), Excell macros, charting in Excel, advanced features, and the general use of Excel. This does not provide a general Excel tutorial nor the basics of using a spreadsheet. It provides specific answers to using Microsoft Excel only. If you do not see your Excel question answered in this area then please ask an Excel question here


All Answers

Answers by Expert:

Ask Experts


Tom Ogilvy


Selected as an Excel MVP by Microsoft since 1999. Answering Excel questions in Allexperts since its inception in 2001. Able to answer questions on almost all aspects of Excel's internal capabilities. If seeking a VBA solution, please specify that in your question itself so I give you the answer you want. [Excel has weak protection - if you are distributing an application, I don't answer questions on how to protect your project from your users.]


Extensive experience.

Master of Science (MS) degree Operations Research (ORSA)

Awards and Honors
Microsoft MVP in Excel.

©2017 All rights reserved.