简体   繁体   中英

How to run the same VBA code on multiple rows

Firstly I would like to apologize as I am aware this question has been asked and answered multiple times. However I am still really struggling to apply these answers to my situation and I am fairly new to VBA.

Currently I have a loop that runs until a condition is met in Row 8. (see below)

Sub Button1_Click()

 Dim i As Double
 Dim x As Double

   t = Range("K3").Value
   i = Range("C8").Value
   x = Range("E8").Value
   b = Range("B8").Value
   
   Do Until i > (x + t)
       i = i + 0.2
   Loop
     
   i = i - 0.2 - b
   
   
   Range("G8").Value = i

End Sub

This does exactly what I require for Row 8. But I need this code to run on multiple rows, the only value that will be static is cell 'K3' ie: So once it is done on row 8 I need this to now run on Row 9 ('C9','E9','B9','G9') and so on, either this will need to run until row 500, or a count of rows entered, either way should be fine for what I am doing.

Appreciate any help, hopefully I have done this post correctly.

Brad.

There will be a whole heap of people here that will give you a much more complete answer but I'm here to answer your direct question.

If you need to apply other enhancements then that can come with other questions. This will help you learn and progress without throwing a heap of code at you that you're not sure of.

Sub Button1_Click()
    Dim i As Double
    Dim x As Double
    Dim lngRow As Long
    
    t = Range("K3").Value
    
    For lngRow = 8 To 500
        i = Range("C" & lngRow).Value
        x = Range("E" & lngRow).Value
        b = Range("B" & lngRow).Value
        
        Do Until i > (x + t)
            i = i + 0.2
        Loop
          
        i = i - 0.2 - b
            
        Range("G" & lngRow).Value = i
    Next
End Sub

That's a simple way to loop through each row.

Considerations you should make on performance are to do with looping, updating cells constantly, calculations and events when updating cells, etc.

But that answers your question.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM