简体   繁体   English

如何在多行上运行相同的 VBA 代码

[英]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.但是,我仍然很难将这些答案应用于我的情况,而且我对 VBA 还很陌生。

Currently I have a loop that runs until a condition is met in Row 8. (see below)目前我有一个循环运行,直到第 8 行满足条件。(见下文)

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.这正是我对第 8 行所要求的。但我需要这段代码在多行上运行,唯一的值是 static 是单元格'K3',即:所以一旦在第 8 行完成,我现在需要运行它第 9 行('C9'、'E9'、'B9'、'G9')等等,要么这需要运行到第 500 行,要么输入行数,无论哪种方式都适合我正在做的事情.

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.但这回答了你的问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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