Want to win a PS4? Go Premium and enter to win our High-Tech Treats giveaway. Enter to Win

x
?
Solved

copy a vb6 recordset to excel.

Posted on 2004-08-03
7
Medium Priority
?
2,231 Views
Last Modified: 2013-11-25
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?
0
Comment
Question by:rambosh
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 3
  • 3
7 Comments
 
LVL 9

Expert Comment

by:dancebert
ID: 11706732
Are you aware of Excel's ability to populate a worksheet from a passed ADO recordset?

ws.Range("A1").CopyFromRecordset rs
0
 

Author Comment

by:rambosh
ID: 11706829
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?
0
 
LVL 9

Expert Comment

by:dancebert
ID: 11706880
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 >>"
    cn.Open
    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

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

End Sub
0
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

Author Comment

by:rambosh
ID: 11708598
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?
0
 
LVL 9

Accepted Solution

by:
dancebert earned 1000 total points
ID: 11708951
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
    Next

    Exit Sub
   
Oops:
    < 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)
    Next

    Exit Sub
   
Oops:
    <your error handling here>
End Sub
0
 
LVL 1

Expert Comment

by:mcsd2001
ID: 11711227
Hey,

***************************
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
next

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

Curtis



0
 

Author Comment

by:rambosh
ID: 11727149
thanks a bunch for your help. I did get the headers working.
0

Featured Post

Important Lessons on Recovering from Petya

In their most recent webinar, Skyport Systems explores ways to isolate and protect critical databases to keep the core of your company safe from harm.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

There are many ways to remove duplicate entries in an SQL or Access database. Most make you temporarily insert an ID field, make a temp table and copy data back and forth, and/or are slow. Here is an easy way in VB6 using ADO to remove duplicate row…
When designing a form there are several BorderStyles to choose from, all of which can be classified as either 'Fixed' or 'Sizable' and I'd guess that 'Fixed Single' or one of the other fixed types is the most popular choice. I assume it's the most p…
Get people started with the utilization of class modules. Class modules can be a powerful tool in Microsoft Access. They allow you to create self-contained objects that encapsulate functionality. They can easily hide the complexity of a process from…
This lesson covers basic error handling code in Microsoft Excel using VBA. This is the first lesson in a 3-part series that uses code to loop through an Excel spreadsheet in VBA and then fix errors, taking advantage of error handling code. This l…
Suggested Courses

618 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question