VBA和Excel – 循环eecordset

我需要在VBA中循环logging集来填充我的Excel表格。 我想为每一行做这个。

我现在得到的是:

comm.CommandText = str_SQL rec.Open comm Sheets("mySheet").Range("A4").CopyFromRecordset rec 

这工作。 但是当我rec里的索引changeX时,我想改变单元格的颜色。

这是可怕的吗? 有人得到另一个解决scheme?

到目前为止,您可以一次输出所有recordsets内容,这比循环每个record每个field (至less对于大型logging集)要快得多。

如果你想实际循环,它会是这样(杂乱和未经testing):

  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 

这可以简化一些,但通常,你将不得不使用两个嵌套循环的logging,并在每个logging的领域。 对于你想做的事情,这可能太笨拙了。

更合理的方法是使用类似的简单方法

 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 

只是格式化你的单元格,独立于你已经处理过的logging集,或者添加条件格式到所说的范围(用vba),这样做有更新自己的优点