VBA & Excel - 循环 eecordset
VBA & Excel - Loop eecordset
我需要在 VBA 中循环一个记录集来填充我的 Excel sheet。我想对每一行都这样做。
我现在得到的是:
comm.CommandText = str_SQL
rec.Open comm
Sheets("mySheet").Range("A4").CopyFromRecordset rec
这行得通。但是当我的 rec 中的索引 change
为 X
.
时,我想更改单元格的颜色
这可能吗?有人有其他解决方案吗?
到目前为止,您一次输出了所有 recordsets
内容,这比在每个 record
中每个 field
循环要快得多(至少对于大型记录集而言)。
如果你想实际循环,它会像这样(混乱且未经测试):
Dim i As Integer, j as Integer
Dim fld As Object
' print headers, starting from A4 to the left
i = 1
j = 4
For Each fld In .Fields
ThisWorkbook.Sheets(mySheet).Cells(j, i).Value = fld.Name
i = i + 1
Next fld
' print record by record, field by field
i = 1
j = j + 1
While Not .EOF
For Each fld In .Fields
ThisWorkbook.Sheets(mySheet).Cells(j, i).Value = fld.Value
' here you could test for something like
' If fld.Name = "change" and fld.Value = "X" Then ThisWorkbook.Sheets(mySheet).Cells(j, i).Interior.Color = vbYellow
i = i + 1
Next fld
j = j + 1
.MoveNext
Wend
这可以进一步简化,但通常,您必须对记录和每条记录中的字段使用两个 嵌套循环。这对于您尝试做的事情来说可能太笨拙了。
一个更合理的方法是使用像
这样简单的东西
Dim cell As Object
For Each cell In Sheets("mySheet").UsedRange '<- replaced UsedRange with the column where "change" is printed, if there's the possibility that "X" is in other columns aswell
With cell
If .Value = "X" Then .Interior.Color = vbYellow
End With
Next cell
仅格式化您的单元格,独立于您已处理的记录集,或向所述范围添加条件格式(使用 vba),这具有自我更新的优势
我需要在 VBA 中循环一个记录集来填充我的 Excel sheet。我想对每一行都这样做。
我现在得到的是:
comm.CommandText = str_SQL
rec.Open comm
Sheets("mySheet").Range("A4").CopyFromRecordset rec
这行得通。但是当我的 rec 中的索引 change
为 X
.
这可能吗?有人有其他解决方案吗?
到目前为止,您一次输出了所有 recordsets
内容,这比在每个 record
中每个 field
循环要快得多(至少对于大型记录集而言)。
如果你想实际循环,它会像这样(混乱且未经测试):
Dim i As Integer, j as Integer
Dim fld As Object
' print headers, starting from A4 to the left
i = 1
j = 4
For Each fld In .Fields
ThisWorkbook.Sheets(mySheet).Cells(j, i).Value = fld.Name
i = i + 1
Next fld
' print record by record, field by field
i = 1
j = j + 1
While Not .EOF
For Each fld In .Fields
ThisWorkbook.Sheets(mySheet).Cells(j, i).Value = fld.Value
' here you could test for something like
' If fld.Name = "change" and fld.Value = "X" Then ThisWorkbook.Sheets(mySheet).Cells(j, i).Interior.Color = vbYellow
i = i + 1
Next fld
j = j + 1
.MoveNext
Wend
这可以进一步简化,但通常,您必须对记录和每条记录中的字段使用两个 嵌套循环。这对于您尝试做的事情来说可能太笨拙了。
一个更合理的方法是使用像
这样简单的东西Dim cell As Object
For Each cell In Sheets("mySheet").UsedRange '<- replaced UsedRange with the column where "change" is printed, if there's the possibility that "X" is in other columns aswell
With cell
If .Value = "X" Then .Interior.Color = vbYellow
End With
Next cell
仅格式化您的单元格,独立于您已处理的记录集,或向所述范围添加条件格式(使用 vba),这具有自我更新的优势