VBA&Excel - Loop eecordset

问题描述:

我需要循环VBA中的记录集来填充我的Excel表格。我想为每一行都做这件事。VBA&Excel - Loop eecordset

我现在所得到的是:

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

这工作。但是当我的记录中的索引changeX时,我想更改单元格的颜色。

这是possbile?有人得到另一种解决方案?

到目前为止,您一次输出所有recordsets内容,这比每(至少对于大型记录集)中的每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 

这可以简化相当多一些,但一般来说,你将不得不使用记录的嵌套循环以及每条记录中的字段。对于你想做的事情,这可能太笨拙了。

较为合理的做法是使用一些简单的像

只是格式化你的细胞,独立于你已经处理过的记录的,或添加条件格式表示的范围(使用VBA),它具有更新本身的优势

+0

为我工作。谢谢。 –