views:

40

answers:

1

Hi. I would like to open a connection to SQL database, and then have access to individual cells. I have an example that uses PivotTableWizard (presented below). I would like to know of a way that does not have anything to do Pivot Tables - I would like to iterate cell-by-cell. Or is this PivotTableWizard suitable for that purpose also?

The example mentioned:

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

A: 

If you want to iterate cell by cell, you could do something like this:

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

The above code iterates through the first 100 rows and the first 25 columns and prints out the cell address and its value in the Debug Window in the Visual Basic Editor.

Ben McCormack
Thank you. But the essence is how to get the data from database into the cells.
karolrvn
@Karol In that case, you can simply use the "Get External Data" feature in Excel. In older versions of Excel, it's located under Data > Get External Data > New Database Query.
Ben McCormack
Thx. Could i use it in an automated way? The end user of this solution should have to do as few manual steps as possible. I could probably record a macro while doing what you suggested and see what code gets recorded - and then embed similar code in the target sheet file.
karolrvn
@Karol Regarding recording a macro, that's exactly what I would do. I used to remember off the top of my head what code to run, but I learned how to do exactly what you're looking for by digging into macro code. If I remember correctly, it's not the cleanest code, but it's not too hard to figure out and see where you need to input your SQL code.
Ben McCormack