在excel中的vba中迭代数据库查询结果

时间:2010-08-05 11:01:12

标签: sql excel vba cell

我想打开与SQL数据库的连接,然后可以访问单个单元格。我有一个使用PivotTableWizard的例子(如下所示)。我想知道一种没有任何事情要做的数据透视表 - 我想逐个细胞地迭代。或者这个数据透视表向导也适用于那个目的吗?

提到的例子:

ConnectionString = "Driver={SQL Server};Server=Serversql11;Persist Security Info=False;Integrated Security=SSPI;Database=DB_IC;"

PivotName = "Talks"

QArray = Array(ConnectionString, _
"exec dbo.talksReport '" & CStr(param_date) & "'")

Worksheets("Talks").PivotTableWizard xlExternal, QArray, Worksheets("Talks").Range("A1"), PivotName

TIA /卡罗尔

1 个答案:

答案 0 :(得分:0)

如果你想逐个细胞地迭代,你可以这样做:

Sub PrintCellContentsToDebugWindow()
  Dim ws As Worksheet
  Dim rng As Range
  Dim intCounterRow As Integer
  Dim intCounterCol As Integer
  Dim intMaxRow As Integer
  Dim intMaxCol As Integer

  Set ws = ActiveSheet   'OR   '
  'Set ws = ActiveWorkbook.Sheets("Sheet1")   '

  intCounterRow = 1
  intCounterCol = 1
  intMaxRow = 100
  intMaxCol = 25

  Do While intCounterCol <= intMaxCol
    intCounterRow = 1
    Do While intCounterRow <= intMaxRow
      Set rng = ws.Cells(intCounterRow, intCounterCol)
      Debug.Print rng.Address & "    " & rng.Value

      intCounterRow = intCounterRow + 1
    Loop
    intCounterCol = intCounterCol + 1
  Loop

End Sub

上面的代码遍历前100行和前25列,并在Visual Basic编辑器的Debug窗口中打印出单元格地址及其值。