• Status: Solved
  • Priority: Medium
  • Security: Public
  • Views: 2276
  • Last Modified:

copy a vb6 recordset to excel.

I'm looking for a function that would be similar to this command in Visual FoxPro. If you have query results in foxpro, you can say "Copy to (filename).xls type xls" and it generates an excel file with your data. Is there a similar funciton in VB 6.0? I've already generated spreadsheets manually by creating a reference to an excel object and populating all of the cells. This is very time consuming when you have multiple spreadsheets to generate. What I want to do is get a recordset and copy that whole recordset to a spreadsheet. I do not need headers, titles, etc. Is there anyway possible to do this?
  • 3
  • 3
1 Solution
Are you aware of Excel's ability to populate a worksheet from a passed ADO recordset?

ws.Range("A1").CopyFromRecordset rs
ramboshAuthor Commented:
No. How would you do that? Looks like you have to have an instance of excel open in vb? As well as an instance of a workbook and worksheet? (I imagine in your example, "ws" stands for the instance of the worksheet?) Say if I have a recordset called RecXLData. Would my command be:  ws.range("A1").copyfromrecordset RecXLData? Does it only copy the data? or the field names as well?
Here is some working code demonstrating the CopyFromRecordset method.  This leaves Excel open.  If you wish to save the spreadsheet to a file, read the comments.  It would be easy to convert this to a reusable sub where one passes in the recordset and a filename to save the Excel file to.

Private Sub doIt()
    Dim oXL As Excel.Application: Set oXL = New Excel.Application
    If Not IsObject(oXL) Then
        MsgBox "You need Microsoft Excel to use this function", vbCritical + vbOKOnly, "Excel Error"
        Exit Sub
    End If
    Dim oBookXL As Excel.Workbook: Set oBookXL = oXL.Workbooks.Add
    Dim oSheetXL As Excel.Worksheet:  Set oSheetXL = oXL.ActiveSheet
'' set these to false if you're saving to a file without opening Excel
    oXL.UserControl = True
    oXL.Visible = True
    Dim cn As ADODB.Connection: Set cn = New ADODB.Connection
    cn.ConnectionString = "Provider=SQLOLEDB.1;Integrated Security=SSPI;Persist Security Info=False;Initial Catalog=Pubs;Data Source=<< your database here >>"
    Dim rs As ADODB.Recordset: Set rs = cn.Execute("SELECT * FROM Authors")
    oSheetXL.Range("A1").CopyFromRecordset rs

'    Uncomment these to save to a file
'    oXL.ActiveWorkbook.SaveAs sPathAndFileName, xlCSV
'    oXL.Quit

    Set cn = Nothing
    Set oSheetXL = Nothing
    Set oBookXL = Nothing
    set oXL = nothing

End Sub
Cloud Class® Course: C++ 11 Fundamentals

This course will introduce you to C++ 11 and teach you about syntax fundamentals.

ramboshAuthor Commented:
ok. I got the data to save to the spreadsheet from the above function. Is there a way to set the column names or insert a row into row 1 with the column headers. I tried, but it didn't like it. I know when you are writing rows, you use syntax like for i = 1 to ???. .range("A"&i).value = xxxxx. Since the columns are character, I was sure how to do it if the number of columns is not predetermined. Any suggestions?
By shear concidence, one of my tasks today was to write a library function to create an XL file from a recordset.  I'm not done yet, but I got the header parts done.

snippet of Calling code:
       ' two types of headers.  One uses field names, other uses array,
       ' e.g., p_vHeaders_ = arrray("col1Head","col2Head" ...)

        Dim sStartCell As String: sStartCell = "A1"
        If p_IsFieldNamesAsHeaders Then
            HeadersFromFieldNames oXL, p_rs
            sStartCell = "A2"
        End If
        If Not IsMissing(p_vHeaders_) Then
            HeadersFromArray oXL, p_vHeaders_
            sStartCell = "A2"
        End If
        ' showtime
        oSheetXL.Range(sStartCell).CopyFromRecordset p_rs

'' ==== called ========

Private Sub HeadersFromFieldNames(p_oXl As Excel.Application _
            , p_rs As adodb.Recordset)

    On Error GoTo Oops

    Dim lCol As Long: lCol = 1
    Dim oFld As adodb.Field
    For Each oFld In p_rs.Fields
        p_oXl.ActiveSheet.Cells(1, lCol).Value = oFld.Name
        lCol = lCol + 1

    Exit Sub
    < your error handling here>
end sub

Private Sub HeadersFromArray(p_oXl As Excel.Application _
            , p_vHeaders_)

    On Error GoTo Oops

    Dim ii As Long
    For ii = 0 To UBound(p_vHeaders_)
        p_oXl.ActiveSheet.Cells(1, ii + 1).Value = p_vHeaders_(ii)

    Exit Sub
    <your error handling here>
End Sub

ADO Recordset Method

GetString(StringFormat, NumRows, ColumnDelimiter, RowDelimiter, NullExpr)

dim strValues as string
dim strFields as string
dim fld as ADODB.Field
dim strFile as string
dim rst ad ADODB.Recordset

rst.open query, con

for each fld in rst.fields
    strFields = strFields & fld.name & vbTab

strFields = Left(strFields,len(strFields) - 1) & vbCrLf

strValues = rst.GetString(adClipString, , vbTab, vbCrLf, "")

strFile = strfields & strvalues

open "c:\test.xls" for binary as #1
put #1,,strFile  
close #1

hope this helps


ramboshAuthor Commented:
thanks a bunch for your help. I did get the headers working.
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

Join & Write a Comment

Featured Post

Cloud Class® Course: SQL Server Core 2016

This course will introduce you to SQL Server Core 2016, as well as teach you about SSMS, data tools, installation, server configuration, using Management Studio, and writing and executing queries.

  • 3
  • 3
Tackle projects and never again get stuck behind a technical roadblock.
Join Now