Solved

Writing record to Excel

Posted on 2011-03-25
6
370 Views
Last Modified: 2013-11-27
I have a table with a column of month end dates.  I also have an .xls file for each of those dates.  Those files are right now identical except for the file name which is based on the month end date, i.e., R1000_20101231.xls.   I need to write the date into a single cell on each excel spreadsheet.  I have used DoCmd.TransferSpreadsheet acExport before to take an entire query and write it to a spreadsheet but is there a way to write a single record to a single excel cell, i.e., cell A2?

Thanks for any help!
0
Comment
Question by:kobys
  • 3
  • 2
6 Comments
 
LVL 119

Accepted Solution

by:
Rey Obrero earned 500 total points
ID: 35217692
see the methods from this link

Using Automation to Transfer Data to Microsoft Excel
http://support.microsoft.com/?kbid=210288
0
 

Author Comment

by:kobys
ID: 35218022
Capricorn1,

Thanks for the reference!   I'm getting a "Subscript out of range" error at the line: mysheet.Application.windows("Y:\Susan and Rob\Equities\R1000\R1000_" & TxtDate & ".xls").Visible = True

 
Public Sub WriteDates()
' Write month-end dates to files

Dim mysheet As Object
Dim xlApp As Object
Dim CurrDate As Date
Dim rsDates As Recordset
Dim TxtDate As String

' Set object variable equal to the OLE object.
Set xlApp = CreateObject("Excel.Application")

Set rsDates = CurrentDb.OpenRecordset("ME_Trade_Dates")
rsDates.MoveFirst

' Loop through all Months
Do While Not rsDates.EOF
    CurrDate = rsDates.fields("[ME_TD]")
    TxtDate = Format(CurrDate, "yyyymmdd")
    Set mysheet = xlApp.workbooks.Open("Y:\Susan and Rob\Equities\R1000\R1000_" & TxtDate & ".xls").Sheets(1)

' Put the value of the ToExcel text box into the cell on the
' spreadsheet and make the cell bold.
    mysheet.cells(2, 1).Value = CurrDate

' Set the Visible property of the sheet to True, save the
' sheet, and quit Microsoft Excel.
    mysheet.Application.windows("Y:\Susan and Rob\Equities\R1000\R1000_" & TxtDate & ".xls").Visible = True
    mysheet.Application.activeworkbook.Save
    mysheet.Application.activeworkbook.Close
    
    rsDates.MoveNext

Loop

xlApp.Quit

' Clear the object variable.
Set mysheet = Nothing

rsDates.Close

End Sub

Open in new window


What does this line do?

Thanks!
0
 

Author Comment

by:kobys
ID: 35218060
If I take that line out, the code seems to work but when I look at the Excel file, all of the cells referencing the cell I wrote say #NAME?.  The date looks perfectly fine and it is in the right cell.  What's going on?

Thanks.
0
Ransomware-A Revenue Bonanza for Service Providers

Ransomware – malware that gets on your customers’ computers, encrypts their data, and extorts a hefty ransom for the decryption keys – is a surging new threat.  The purpose of this eBook is to educate the reader about ransomware attacks.

 

Author Comment

by:kobys
ID: 35218068
Forget my last comment.  It's an issue with Bloomberg.
0
 
LVL 31

Expert Comment

by:Helen_Feddema
ID: 35222510
To write a single record, you could create a filtered recordset, using code like the sample below to get just the single record you want, then export that saved query to Excel.
[sample code fragment using the procedure]

   Dim dbs As DAO.Database
   Dim lngCount As Long
   Dim lngID As Long
   Dim rpt As Access.Report
   Dim rst As DAO.Recordset
   Dim strPrompt As String
   Dim strQuery As String
   Dim strRecordSource As String
   Dim strReport As String
   Dim strSQL As String
   Dim strTitle As String
   
   strRecordSource = "tblInventoryItemsComponents"
   strQuery = "qryTemp"
   Set dbs = CurrentDb

   'Numeric filter
   lngID = Nz(Me![ID])
   If lngID <> 0 Then
      strSQL = "SELECT * FROM " & strRecordSource & " WHERE " _
         & "[ID] = " & lngID & ";"
   End If

   'String filter
   strInventoryCode = Nz(Me![InventoryCode])
   If strInventoryCode <> "" Then
      strSQL = "SELECT * FROM " & strRecordSource & " WHERE " _
         & "[InventoryCode] = " & Chr$(39) & strInventoryCode & Chr$(39) & ";"
   End If

   'Date range filter from custom database properties
   dteFromDate = CDate(GetProperty("FromDate", ""))
   dteToDate = CDate(GetProperty("ToDate", ""))
   strSQL = "SELECT * FROM " & strRecordSource & " WHERE " _
      & "[dteDateReceived] Between " & Chr(35) & dteFromDate _
      & Chr(35) & " And " & Chr(35) & dteToDate & Chr(35) & ";"

   'Date range filter from controls
   If IsDate(Me![txtFromDate].Value) = True Then
      dteFromDate = CDate(Me![txtFromDate].Value)
   End If

   If IsDate(Me![txtToDate].Value) = True Then
      dteToDate = CDate(Me![txtToDate].Value)
   End If

   strSQL = "SELECT * FROM " & strRecordSource & " WHERE " _
      & "[dteDateReceived] Between " & Chr(35) & dteFromDate _
      & Chr(35) & " And " & Chr(35) & dteToDate & Chr(35) & ";"

   Debug.Print "SQL for " & strQuery & ": " & strSQL
   lngCount = CreateAndTestQuery(strQuery, strSQL)
   Debug.Print "No. of items found: " & lngCount
   If lngCount = 0 Then
      strPrompt = "No records found; canceling"
      strTitle = "Canceling"
      MsgBox strPrompt, vbOKOnly + vbCritical, strTitle
      GoTo ErrorHandlerExit
   Else
      'Use this line if you need a recordset
      Set rst = dbs.OpenRecordset(strQuery)
   End If

   'Use SQL string as the record source of a form
   strFormName = "fpriLoadSoldPackingSlip"
   DoCmd.OpenForm FormName:=strFormName, _
      view:=acDesign
   Set frm = Forms(strFormName)
   frm.RecordSource = strSQL
   DoCmd.OpenForm FormName:=strFormName, _
      view:=acNormal
   
   'Use SQL string as the record source of a report
   strReport = "rptLoadSold"
   DoCmd.OpenReport ReportName:=strReport, _
      view:=acViewDesign, _
      windowmode:=acHidden
   Set rpt = Reports(strReport)
   rpt.RecordSource = strSQL
   DoCmd.OpenReport ReportName:=strReport, _
      view:=acViewNormal, _
      windowmode:=acWindowNormal

   'The report has the filtered query as its record source

=========================

Public Function CreateAndTestQuery(strTestQuery As String, _
   strTestSQL As String) As Long
'Created by Helen Feddema 28-Jul-2002
'Last modified 6-Dec-2009

On Error Resume Next
   
   Dim qdf As DAO.QueryDef
   Dim rst As DAO.Recordset
   
   'Delete old query
   Set dbs = CurrentDb
   dbs.QueryDefs.Delete strTestQuery

On Error GoTo ErrorHandler
   
   'Create new query
   Set qdf = dbs.CreateQueryDef(strTestQuery, strTestSQL)
   
   'Test whether there are any records
   Set rst = dbs.OpenRecordset(strTestQuery)
   With rst
      .MoveFirst
      .MoveLast
      CreateAndTestQuery = .RecordCount
   End With
   
ErrorHandlerExit:
   Exit Function

ErrorHandler:
   If Err.Number = 3021 Then
      CreateAndTestQuery = 0
      Resume ErrorHandlerExit
   Else
   MsgBox "Error No: " & Err.Number _
      & " in CreateAndTestQuery procedure; " _
      & "Description: " & Err.Description
   End If
   
End Function

Open in new window

0
 
LVL 31

Expert Comment

by:Helen_Feddema
ID: 35222513
The Numeric filter example would do for a standard AutoNumber key field.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

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

A simple tool to export all objects of two Access files as text and compare it with Meld, a free diff tool.
Describes a method of obtaining an object variable to an already running instance of Microsoft Access so that it can be controlled via automation.
In Microsoft Access, learn the trick to repeating sub-report headings at the top of each page. The problem with sub-reports and headings: Add a dummy group to the sub report using the expression =1: Set the “Repeat Section” property of the dummy…
In Microsoft Access, when working with VBA, learn some techniques for writing readable and easily maintained code.

920 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

Need Help in Real-Time?

Connect with top rated Experts

16 Experts available now in Live!

Get 1:1 Help Now