vba - 对于 Excel VBA 中的嵌套循环
问题描述
我有一个 For 循环来查看列并且需要跳过两列。当我运行此代码时,第二个 For 循环(使用 iCol)不起作用。
当我在循环外进行测试时,循环内的代码运行良好。我尝试了不同的选项来从 For 循环(选择案例)中排除两列,但没有任何效果。
Dim rng As Range
Dim n As Long
Dim iRow As Long
Dim iCol As Long
Dim NameColNum As Integer
Dim LNameColNum As Integer
Dim DoBColNum As Integer
Dim SColNum As Integer
Dim JColNum As Integer
' Sets data range
Set rng = Range(Range("A1"), Range("A" & Rows.Count).End(xlUp))
NameColNum = Application.Match("First Name", rng.EntireRow(1), 0)
LNameColNum = Application.Match("Last Name", rng.EntireRow(1), 0)
DoBColNum = Application.Match("Birth Date", rng.EntireRow(1), 0)
' For S and J cases
SColNum = Application.Match("Created User ID", rng.EntireRow(1), 0)
JColNum = Application.Match("W Name", rng.EntireRow(1), 0)
For iRow = 2 To rng.Rows.Count
If rng.Cells(iRow, NameColNum) = rng.Cells(iRow + 1, NameColNum) And _
rng.Cells(iRow, LNameColNum) = rng.Cells(iRow + 1, LNameColNum) And _
rng.Cells(iRow, DoBColNum) = rng.Cells(iRow + 1, DoBColNum) Then
If rng.Cells(iRow, SColNum).Value = "STAGE" Then
rng.EntireRow(iRow).Interior.ColorIndex = 3
rng.EntireRow(iRow + 1).Interior.ColorIndex = 3
End If
If rng.Cells(iRow, JColNum) = "Smith" Then
rng.EntireRow(iRow).Interior.ColorIndex = 4
rng.EntireRow(iRow + 1).Interior.ColorIndex = 4
End If
For iCol = DoBColNum + 1 To rng.Columns.Count
If iCol <> SColNum And iCol <> JColNum Then
If rng.Cells(iRow, iCol).Value <> rng.Cells(iRow + 1, iCol).Value And _
rng.EntireRow(iRow).Interior.ColorIndex = -4142 Then
rng.EntireRow(iRow).Interior.ColorIndex = iCol
rng.EntireRow(iRow + 1).Interior.ColorIndex = iCol
End If
End If
Next 'iCol
End If
Next 'iRow
解决方案
rng.Columns.Count
总是等于 1,因为你限制rng
在你的Set
行上的 A 列。因此,您的第二个循环将永远不会运行(您正在尝试循环4 to 1
等)。
相反,更改Set rng = Range(Range("A1"), Range("A" & Rows.Count).End(xlUp))
为包含您使用的所有列,并从另一行的列 A 中获取最后一行值。
建议修复:
Dim lastrow As Long
lastrow = Cells(Rows.Count, "A").End(xlUp).Row
' Sets data range
Set rng = Range(Range("A1"), Range("S" & lastrow))
推荐阅读
- python - 从 s3 读取 .pptx 文件
- python - 使用外键模型 django restframework 创建视图
- c# - 将不同 URL 的 HTTP 请求名称解析缓存到同一主机。可能的?
- python - 使用 lambda 函数在 python 排序中的 [k] 是什么?
- python - 使用 python 3.9.1 在窗口 10 上安装 tensorflow 时出错
- ios - HealthKit,内置睡眠检测在睡眠计划之外不起作用
- java - azure 广告令牌过期怎么办?
- shell - 如何使用 Automator 重命名和移动下载到“下载”的文件,无论是否使用 Applescript、Shell 脚本或 Javascript?
- xamarin.forms - 使用 MVVM 的 Xamarin.forms 生命周期方法
- angular - Angular 11类型未定义不可分配给类型'T'