Results 1 to 7 of 7

Thread: CopyRecordset, how to use to transfer query results from grid to Excel

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Mar 2002
    Posts
    131

    CopyRecordset, how to use to transfer query results from grid to Excel

    Hi, how do you use CopyRecordset to transfer query results from grid to Excel? It must first check if Excel exists then transfers and launches the whole Excel app. If the Excel app is already open it just transfers it to a new worksheet.

    Also, a problem on grid. There are two grids one for the items called grd and the other is for its subtotal called grdSub. When grd returns a query it calculates the subtotal and it displayed on grdSub. The problem is when there is no query result the grdSub's subtotal is still there. grdSub should be blank because there was no query returned and therefore no subtotal.

    Thank you in advance.

    God bless,
    Alvin

  2. #2
    PowerPoster Beacon's Avatar
    Join Date
    Jan 2001
    Location
    Pub Floor
    Posts
    3,188
    1)
    VB Code:
    1. Option Explicit
    2.  
    3. Dim objXL As Excel.Application
    4. Dim objWkb As Excel.Workbook
    5. Dim objSht As Excel.Worksheet
    6.  
    7. Private Sub cmdExport_Click()
    8.  
    9. rs.Open "Select * From table Where fieldname ='" & uname & "", cn, adOpenKeyset, adLockPessimistic, adCmdText
    10. Dim intMaxCol As Integer
    11. Dim intMaxRow As Integer
    12. Dim tempStr As Integer
    13.  
    14. intMaxCol = rs.Fields.Count
    15. If rs.RecordCount > 0 Then
    16. rs.MoveLast: rs.MoveFirst
    17. intMaxRow = rs.RecordCount
    18. tempStr = rs.RecordCount
    19. Set objXL = New Excel.Application
    20. With objXL
    21. .Visible = True
    22. Set objWkb = .Workbooks.Add
    23. Set objSht = objWkb.Worksheets(1)
    24.  
    25. Dim f As Field, fCount As Integer, FieldStart As Range
    26. Set FieldStart = objWkb.Worksheets(1).Range("A1")
    27. For Each f In rs.Fields
    28. FieldStart.Offset(0, fCount).Value = f.Name
    29. With objXL.Cells.Font
    30. .Name = "Arial"
    31. .Bold = False
    32. .Size = 9
    33. End With
    34. fCount = fCount + 1
    35. Next f
    36. With objSht
    37. .Range(.Cells(2, 1), .Cells(intMaxRow + 1, intMaxCol + 1)).CopyFromRecordset rs
    38. End With
    39. .Cells(2, 1).CurrentRegion.EntireColumn.AutoFit
    40. End With
    41. End If
    42. rs.Filter = ""
    43. rs.Close
    44. End Sub

  3. #3

    Thread Starter
    Addicted Member
    Join Date
    Mar 2002
    Posts
    131

    Unhappy cn error, variable not defined it said

    Thank you very much but there were error, starting with cn as variable not defined. I modified it and to involves SQL and date using # sign for a date range from txtFrom to txtTo (Ex 8/8/00 to 8/8/02- sya for two annual reports of items received or bought from supplier)


    Option Explicit
    '------------------------------
    'FOR THE cmdExcel Test button to transfer to Excel

    Dim objXL As Excel.Application
    Dim objWkb As Excel.Workbook
    Dim objSht As Excel.Worksheet
    ______________________________
    Private Sub cmdExcel_Click()

    Dim d As Database
    Dim rs As Recordset
    Dim q As QueryTable
    Set d = OpenDatabase(App.Path & "\Parts Inventory.mdb")
    Set rs = d.OpenRecordset("SELECT * FROM [Receiving Table] WHERE Received BETWEEN #" & txtFrom & "# AND #" & txtTo & "#")

    rs.Open "SELECT * FROM [Receiving Table] WHERE Received BETWEEN #" & txtFrom & "# AND #" & txtTo & "#", cn, adOpenKeyset, adLockPessimistic, adCmdText
    Dim intMaxCol As Integer
    Dim intMaxRow As Integer
    Dim tempStr As Integer

    intMaxCol = rs.Fields.Count
    If rs.RecordCount > 0 Then
    rs.MoveLast: rs.MoveFirst
    intMaxRow = rs.RecordCount
    tempStr = rs.RecordCount
    Set objXL = New Excel.Application
    With objXL
    .Visible = True
    Set objWkb = .Workbooks.Add
    Set objSht = objWkb.Worksheets(1)

    Dim f As Field, fCount As Integer, FieldStart As Range
    Set FieldStart = objWkb.Worksheets(1).Range("A1")
    For Each f In rs.Fields
    FieldStart.Offset(0, fCount).Value = f.Name
    With objXL.Cells.Font
    .Name = "Arial"
    .Bold = False
    .Size = 9
    End With
    fCount = fCount + 1
    Next f
    With objSht
    .Range(.Cells(2, 1), .Cells(intMaxRow + 1, intMaxCol + 1)).CopyFromRecordset rs
    End With
    .Cells(2, 1).CurrentRegion.EntireColumn.AutoFit
    End With
    End If
    rs.Filter = ""

    rs.Close
    Set d = Nothing
    Set r = Nothing

    End Sub

    -----------------
    Btw I've slved the grdSub and grdTot display problem, was simple just repeat the SQL at the beginninof the code so it find nothing and the grids follow. It sort of refresh the grids to not display anything

  4. #4
    PowerPoster Beacon's Avatar
    Join Date
    Jan 2001
    Location
    Pub Floor
    Posts
    3,188
    cn is the ado connection string.

    Your using DAO so it should be db i guess! You'll have to alter it.

    b

  5. #5

    Thread Starter
    Addicted Member
    Join Date
    Mar 2002
    Posts
    131

    db still variable not defined

    Hi, still says variable not defined on db.

    I wonder what's the solution here. Btw, I have tested this code it works but when you click cancel when it's on the save dialog box with Book1.xls it returns an error.

    This is the code I currently use ti transfer query result to Excel but it also has other problems, like it doesn't launch the whole Excel with all the tools:


    Private Sub mnuFileExcel_Click()
    Me.MousePointer = 11
    '-------------------------------------------------------------------------------------------------------------------------
    'Check first if there is a record to save
    With datDummy
    'strTo = txtTo.Text
    sSQL = ("SELECT * FROM [Receiving Table] WHERE Received BETWEEN #" & txtFrom & "# AND #" & txtTo & "#")
    .RecordSource = sSQL
    .Refresh

    'If no record is found
    If .Recordset.RecordCount = 0 Then
    intMsg = MsgBox("There is no record to save yet", vbOKOnly + vbExclamation, Empty)
    Me.MousePointer = 0
    Exit Sub
    End If
    End With
    '-------------------------------------------------------------------------------------------------------------------------

    Dim d As Database
    Dim r As Recordset
    Dim q As QueryTable
    Set d = OpenDatabase(App.Path & "\Parts Inventory.mdb")
    Set r = d.OpenRecordset("SELECT * FROM [Receiving Table] WHERE Received BETWEEN #" & txtFrom & "# AND #" & txtTo & "#")


    Dim x As New Excel.Application

    x.Application.DisplayAlerts = False
    x.Visible = False

    Dim w As Worksheet
    x.Workbooks.Add
    Set w = x.Worksheets(1)
    Set q = w.QueryTables.Add(r, w.Range("A1"))
    q.Refresh (True)

    x.Workbooks.Application.SaveWorkspace ' ("c:\pibkrecv.xls")
    x.Quit
    MsgBox "It has been saved", vbInformation, Empty
    'x.SaveChanges = False


    Set d = Nothing
    Set r = Nothing
    On Error GoTo exit2

    exit2:
    Exit Sub
    MsgBox "Error", vbInformation, "Not Saved, Excel application may not have been installed"
    Me.MousePointer = 0
    End Sub


    God bless,
    Alvin

  6. #6
    Don't Panic! Ecniv's Avatar
    Join Date
    Nov 2000
    Location
    Amsterdam...
    Posts
    5,343
    Originally posted by Beacon
    VB Code:
    1. Option Explicit
    2.  
    3. Private Sub cmdExport_Click()
    4.  
    5. Dim db as database, rs as recordset
    6. Dim objXL As Excel.Application
    7. Dim objWkb As Excel.Workbook
    8. Dim objSht As Excel.Worksheet
    9.  
    10. Dim intMaxCol As Integer
    11. Dim intMaxRow As Integer
    12. Dim tempStr As Integer
    13. Dim f As Field, fCount As Integer, FieldStart As Range
    14.  
    15. on error resume next
    16.  
    17. set db = dbengine(0)(0).opendatbase("dbpath",false,false)
    18. set rs = db.openrecordset("sql statement")
    19. 'rs.Open "Select * From table Where fieldname ='" & uname & "", cn, adOpenKeyset, adLockPessimistic, adCmdText
    20.  
    21. '---- sets max records
    22. intMaxCol = rs.Fields.Count
    23. If rs.RecordCount > 0 Then
    24. rs.MoveLast: rs.MoveFirst
    25. intMaxRow = rs.RecordCount
    26. tempStr = rs.RecordCount
    27.  
    28. '---- open excel and get objects - [i]sheet[/i]
    29. Set objXL = New Excel.Application
    30. With objXL
    31. .Visible = True
    32. Set objWkb = .Workbooks.Add
    33. Set objSht = objWkb.Worksheets(1)
    34.  
    35. '---- deals with fonts - although you could do this with .cells and format property... ;) just an idea
    36. Set FieldStart = objWkb.Worksheets(1).Range("A1")
    37. For Each f In rs.Fields
    38. FieldStart.Offset(0, fCount).Value = f.Name
    39. With objXL.Cells.Font
    40. .Name = "Arial"
    41. .Bold = False
    42. .Size = 9
    43. End With
    44. fCount = fCount + 1
    45. Next f
    46.  
    47. '---- drops the recordset into excel
    48. With objSht
    49. .Range(.Cells(2, 1), .Cells(intMaxRow + 1, intMaxCol + 1)).CopyFromRecordset rs
    50. End With
    51. .Cells(2, 1).CurrentRegion.EntireColumn.AutoFit
    52. End With
    53. End If
    54. rs.Filter = ""
    55. rs.Close
    56.  
    57. set rs = nothing
    58. set db = nothing
    59. End Sub
    I've added some notes in there and amended (quickly) to what I think should work - no guarentees but should give you a start on the right code using beacons coding



    Vince

    BOFH Now, BOFH Past, Information on duplicates

    Feeling like a fly on the inside of a closed window (Thunk!)
    If I post a lot, it is because I am bored at work! ;D Or stuck...
    * Anything I post can be only my opinion. Advice etc is up to you to persue...

  7. #7

    Thread Starter
    Addicted Member
    Join Date
    Mar 2002
    Posts
    131

    Opendatabase method not found error

    Hi, there's method not found error. here is the whole code now replaced with App.Path and SQL for my project. Other than those two, I did no more modification.

    God bless, Alvin
    _____________

    Dim db As Database, rs As Recordset
    Dim objXL As Excel.Application
    Dim objWkb As Excel.Workbook
    Dim objSht As Excel.Worksheet

    Dim intMaxCol As Integer
    Dim intMaxRow As Integer
    Dim tempStr As Integer
    Dim f As Field, fCount As Integer, FieldStart As Range

    On Error Resume Next

    Set db = DBEngine(0)(0).OpenDatabase(App.Path & "\Parts Inventory.mdb", False, False)
    Set rs = db.OpenRecordset("SELECT [RR No], Sum([Quantity x Price])AS [Subtotal] FROM [Receiving Table]WHERE Received BETWEEN #" & txtFrom.Text & "# AND #" & txtTo.Text & "#")
    'rs.Open "Select * From table Where fieldname ='" & uname & "", cn, adOpenKeyset, adLockPessimistic, adCmdText

    '---- sets max records
    intMaxCol = rs.Fields.Count
    If rs.RecordCount > 0 Then
    rs.MoveLast: rs.MoveFirst
    intMaxRow = rs.RecordCount
    tempStr = rs.RecordCount

    '---- open excel and get objects - sheet
    Set objXL = New Excel.Application
    With objXL
    .Visible = True
    Set objWkb = .Workbooks.Add
    Set objSht = objWkb.Worksheets(1)

    '---- deals with fonts - although you could do this with .cells and format property... just an idea
    Set FieldStart = objWkb.Worksheets(1).Range("A1")
    For Each f In rs.Fields
    FieldStart.Offset(0, fCount).Value = f.Name
    With objXL.Cells.Font
    .Name = "Arial"
    .Bold = False
    .Size = 9
    End With
    fCount = fCount + 1
    Next f

    '---- drops the recordset into excel
    With objSht
    .Range(.Cells(2, 1), .Cells(intMaxRow + 1, intMaxCol + 1)).CopyFromRecordset rs
    End With
    .Cells(2, 1).CurrentRegion.EntireColumn.AutoFit
    End With
    End If
    rs.Filter = ""
    rs.Close

    Set rs = Nothing
    Set db = Nothing

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width