excel - Vba for loop to repeat code output for cell rage
问题描述
How can I make a for loop to repeat this code between N5 to N11
Dim rw As Long
If Range("K6") = True Then 'Holiday Check
rw = [RandBetween(6,25)]
Range("N5") = Cells(rw, 21)
ElseIf Range("I6") = True Then 'Weekend Check
rw = [RandBetween(5,28)]
Range("N5") = Cells(rw, 20)
Else 'Else Weekday
rw = [RandBetween(5,65)]
Range("N5") = Cells(rw, 19)
End If
Thank you in advance :)
解决方案
You can see the documentation for For...Next and For Each...Nextloops which explains how the syntax works for each of the loops.
To achieve your goal, you can consider the following:
- Use a variable for either your cell reference or row number
- Increment that variable with each step of your loop
- Replace the hard coded range reference to reference either the cell or row number variable.
I will demonstrate the For Each...Next
method.
Something like this:
Private Sub UsingAForLoop()
Dim TargetCell As Range
For Each TargetCell In Range("N5:N11")
If Range("K6") = True Then 'Holiday Check
rw = [RandBetween(6,25)]
TargetCell = Cells(rw, 21)
ElseIf Range("I6") = True Then 'Weekend Check
rw = [RandBetween(5,28)]
TargetCell = Cells(rw, 20)
Else 'Else Weekday
rw = [RandBetween(5,65)]
TargetCell = Cells(rw, 19)
End If
Next TargetCell
End Sub
This example loops through each cell in the range Range("N5:N11")
and follows your if logic each time. When the condition is met, the TargetCell
for that iteration will be populated with the data per your Cells()
reference.
If you need to change the other references as part of your IF...Then
statements you can follow the same logic.
推荐阅读
- go - 使用反射和循环修改结构值
- reactjs - 根据屏幕的大小(响应式)渲染不同的布局
- c++ - 如何从函数返回负值?
- c++ - 如果未提供默认构造函数,如何使用流提取运算符?
- python - 网络硒测试找不到元素
- vb.net - 该进程无法访问文件“路径”,因为在使用 FileSystemWatcher 时它正被另一个进程使用
- spring-boot - log4j2 Slf4j LoggerFactory.getILoggerFactory 获取的记录器只能读取没有配置文件的默认 log4j.xml
- android-studio - 最低数量 获得广告印象的广告请求
- java - 如何将字符串格式的给定日期视为 est 并将其转换为 java 中的 utc?
- python-3.x - Python3 代码帮助无法向用户显示总数