簡體   English   中英

在Excel中的VBA中遍歷數據庫查詢結果

[英]iterate over database query results in vba in excel

我想打開一個到SQL數據庫的連接,然后可以訪問單個單元格。 我有一個使用PivotTableWizard的示例(如下所示)。 我想知道一種與數據透視表無關的方法-我想逐個單元地迭代。 還是此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 / Karol

如果要逐個單元地迭代,可以執行以下操作:

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編輯器的“調試”窗口中打印出單元地址及其值。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM