473,387 Members | 1,394 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,387 software developers and data experts.

Clear Excel Worksheet Contents Before Transferring Query From Access 2003

Hi, very much a novice in VBA and I've been trying to write a bit of code that exports multiple queries from my Access database to Excel. This works brilliantly but I'd like to clear the contents of each Excel worksheet (columns A:H) before the data transfer takes place. Can anyone help ?

Code I'm using is....

Expand|Select|Wrap|Line Numbers
  1. Private Sub Command4_Click()
  2. Dim lngColumn As Long
  3. Dim xlx As Object, xlw As Object, xls As Object, xlc As Object
  4. Dim dbs As DAO.Database
  5.  Dim rst As DAO.Recordset
  6.  Dim blnEXCEL As Boolean, blnHeaderRow As Boolean
  7.  
  8.  blnEXCEL = False
  9.  blnHeaderRow = True
  10.  
  11.  On Error Resume Next
  12.  Set xlx = GetObject(, "Excel.Application")
  13.  If Err.Number <> 0 Then
  14.        Set xlx = CreateObject("Excel.Application")
  15.        blnEXCEL = True
  16.  End If
  17.  Err.Clear
  18.  On Error GoTo 0
  19.  
  20.  xlx.Visible = True
  21.  
  22. Set xlw = xlx.Workbooks.Open("V:\Ops Timing Collection\OO Database\Risk Registers\Solutions Delivery\RR Examplev2.xlsx")
  23.  
  24. Set xls = xlw.Worksheets("Risks")
  25.  
  26. Set xlc = xls.Range("A1") ' this is the first cell into which data go
  27.  
  28. Set dbs = CurrentDb()
  29. Set rst = dbs.OpenRecordset("q_RiskRegisterOutputRisks", dbOpenDynaset, dbReadOnly)
  30.  
  31. If rst.EOF = False And rst.BOF = False Then
  32.  
  33.       rst.MoveFirst
  34.  
  35.       If blnHeaderRow = True Then
  36.              For lngColumn = 0 To rst.Fields.Count - 1
  37.                    xlc.Offset(0, lngColumn).Value = rst.Fields(lngColumn).Name
  38.                    Next lngColumn
  39.              Set xlc = xlc.Offset(1, 0)
  40.        End If
  41.  
  42.  
  43.       Do While rst.EOF = False
  44.             For lngColumn = 0 To rst.Fields.Count - 1
  45.                   xlc.Offset(0, lngColumn).Value = rst.Fields(lngColumn).Value
  46.             Next lngColumn
  47.             rst.MoveNext
  48.             Set xlc = xlc.Offset(1, 0)
  49.       Loop
  50. End If
  51.  
  52. Set xls = xlw.Worksheets("Controls")
  53.  
  54. Set xlc = xls.Range("A1") ' this is the first cell into which data go
  55.  
  56. Set dbs = CurrentDb()
  57. Set rst = dbs.OpenRecordset("q_RiskRegisterOutputControls", dbOpenDynaset, dbReadOnly)
  58.  
  59. If rst.EOF = False And rst.BOF = False Then
  60.  
  61.       rst.MoveFirst
  62.  
  63.       If blnHeaderRow = True Then
  64.              For lngColumn = 0 To rst.Fields.Count - 1
  65.                    xlc.Offset(0, lngColumn).Value = rst.Fields(lngColumn).Name
  66.              Next lngColumn
  67.              Set xlc = xlc.Offset(1, 0)
  68.        End If
  69.  
  70.  
  71.       Do While rst.EOF = False
  72.             For lngColumn = 0 To rst.Fields.Count - 1
  73.                   xlc.Offset(0, lngColumn).Value = rst.Fields(lngColumn).Value
  74.             Next lngColumn
  75.             rst.MoveNext
  76.             Set xlc = xlc.Offset(1, 0)
  77.       Loop
  78.  
  79. End If
  80.  
  81. Set xls = xlw.Worksheets("Actions")
  82.  
  83. Set xlc = xls.Range("A1") ' this is the first cell into which data go
  84.  
  85. Set dbs = CurrentDb()
  86. Set rst = dbs.OpenRecordset("q_RiskRegisterOutputActions", dbOpenDynaset, dbReadOnly)
  87.  
  88. If rst.EOF = False And rst.BOF = False Then
  89.  
  90.       rst.MoveFirst
  91.  
  92.       If blnHeaderRow = True Then
  93.              For lngColumn = 0 To rst.Fields.Count - 1
  94.                    xlc.Offset(0, lngColumn).Value = rst.Fields(lngColumn).Name
  95.              Next lngColumn
  96.              Set xlc = xlc.Offset(1, 0)
  97.        End If
  98.  
  99.  
  100.       Do While rst.EOF = False
  101.             For lngColumn = 0 To rst.Fields.Count - 1
  102.                   xlc.Offset(0, lngColumn).Value = rst.Fields(lngColumn).Value
  103.             Next lngColumn
  104.             rst.MoveNext
  105.             Set xlc = xlc.Offset(1, 0)
  106.       Loop
  107.  
  108. End If
  109.  
  110. Set xls = xlw.Worksheets("Action Updates")
  111.  
  112. Set xlc = xls.Range("A1") ' this is the first cell into which data go
  113.  
  114. Set dbs = CurrentDb()
  115. Set rst = dbs.OpenRecordset("q_RiskRegisterOutputActionUpdates", dbOpenDynaset, dbReadOnly)
  116.  
  117. If rst.EOF = False And rst.BOF = False Then
  118.  
  119.       rst.MoveFirst
  120.  
  121.       If blnHeaderRow = True Then
  122.              For lngColumn = 0 To rst.Fields.Count - 1
  123.                    xlc.Offset(0, lngColumn).Value = rst.Fields(lngColumn).Name
  124.              Next lngColumn
  125.              Set xlc = xlc.Offset(1, 0)
  126.        End If
  127.  
  128.  
  129.       Do While rst.EOF = False
  130.             For lngColumn = 0 To rst.Fields.Count - 1
  131.                   xlc.Offset(0, lngColumn).Value = rst.Fields(lngColumn).Value
  132.             Next lngColumn
  133.             rst.MoveNext
  134.             Set xlc = xlc.Offset(1, 0)
  135.       Loop
  136.  
  137. End If
  138.  
  139. rst.Close
  140. Set rst = Nothing
  141.  
  142. dbs.Close
  143. Set dbs = Nothing
  144.  
  145.  Set xlc = Nothing
  146.  Set xls = Nothing
  147.  xlw.Close True   ' close the EXCEL file and save the new data
  148.  Set xlw = Nothing
  149.  If blnEXCEL = True Then xlx.Quit
  150.  Set xlx = Nothing
  151. End Sub
Thanks,
Craig
May 16 '14 #1
7 5423
zmbd
5,501 Expert Mod 4TB
Would you be opposed to simply deleting the worksheet and letting the method insert a clean one?
May 20 '14 #2
Hi, thanks for replying. Unfortunately I've got some embedded formulas in the receiving spreadsheet that I don't want to overwrite.

Thanks
May 20 '14 #3
zmbd
5,501 Expert Mod 4TB
darn... thought that would be too easy... (^_^)

Here's the basics, try to code it yourself and if you run into issues, post back the altered code and we'll fine tune it... we work on the teach to fish method (^_^), I do promise that we'll get the code right.

I'm going to translate a few things from your code to my outline
xlx = excelapp
xlw = excelfile
xls = excelsheet
xlc = excelrange < we wont need this for our work

Ok, you already have XLX and XLW setup and it sounds as if you have multiple worksheets so:

- set your excelsheet to the correct index, this starts at 1 and goes in the order of creation.
- Columns are a collection under the sheet object, so... select the columns ("A:H") would select your coulmns a thru h.
- Clearing the selection is an application (excelapp) level method
and we only want to "ClearContents" from the selection
- Finally, we can select the Range "A1" in excelsheet or you can simply leave the cursor where it's at on the worksheet.

repeat for each excelsheet in the excelfile


You might also take a look at the insight article on application automation found here: http://bytes.com/topic/access/insigh...ion-automation mainly over Outlook; however, there's some over Excel too.

I'll be tied up for the next hour or two so, give it try and post back your results.
May 20 '14 #4
Morning Dan, many thanks but I really am a novice and not sure where to start. Anyway

So for the worksheet 'Risks' I've changed...

Set xlc = xls.Range("A1") ' this is the first cell into which data go

to

Set xlc = xls.Range("A:S") ' this is the first cell into which data go

How do I add the 'clearcontents' bit.

Again, apologies for the lack of knowledge.

Thanks, Craig
May 21 '14 #5
zmbd
5,501 Expert Mod 4TB
Totally new to the VBA scene... that's quite OK, we all started there... sort of like walking (^_^)

I'll send you a boiler plate with some tutorials, one covers the basics of VBA and has a few reference links that I hope provide something useful. Check your bytes.com inbox in a little while - Mornings are very busy for me with meetings and follow-ups in the lab.

Assuming that you borrowed the code in the Original Post (OP), I'm going to point out a few places in the code that are key to understanding what we want to do.

>By line 20
it appears that the code has set xlx to be the working excel application object and is making it visible to the end user.
I would have used zexcelapp as the name

>Line 22
This points XLX to the workbook file and then sets the file to be the xlw object. I would have used zexcelfile to indicate that I am working with a stored file and zexcelwb if I was creating a workbook from within code

>Line 24
Now were setting the object xls to be the worksheet of interest (named "Risks") I would have used zexcelsheet

From OP, at this point, it appears that you want to clear the data in xls starting in column A and going thru column H.

You are then going to transfer information into xls

>Line 52 sets xls to point to Worksheet "Controls"

Also from OP it sounds like you want to clear the data in this sheet...

>line 81 sets xls to point to Worksheet "Actions" repeat the clear and data xfer

>Line 110 sets xls to point to Worksheet "Actions Updates" repeat the clear and data xfer

Then after that you start cleaning up.

So what I suggest is that between lines 20 and lines 22
insert code to select the worksheets as a group
insert code to select the columns A:H as a group
Delete just the contents of the selected

Normative at bytes.com is that we teach you how to fish so that you can develop you own code; however, the application-automation isn't always well documented so an exception I think is in order- no?

So where to start, you have an outline of code to work with and then we just need to understand what we need to use to work with the sheets group.

Many people get their intro to VBA via Excel and recording a "macro." Of course I hate the usage of "Macro" to describe VBA programing because when you get to Ms Access Macro does not mean the same as VBA.... anyway, here's the Excel version created via the record macro:

Now if you open excel and record a macro that does the above selection and clear you'll get something like:
Expand|Select|Wrap|Line Numbers
  1. Sheets(Array("query1", "query2", "query3")).Select
  2.     Sheets("query1").Activate
  3.     Columns("A:H").Select
  4.     Selection.ClearContents
  5.     Range("A1").Select
  6.     Sheets("query1").Select
Which we need to translate into the automation code for Access:

Expand|Select|Wrap|Line Numbers
  1. zexcelfile.Worksheets(Array("query1", "query2", "query3")).Select
  2.     zexcelfile.Worksheets("query1").Activate
  3. '
  4. 'here's the quirk. the remaining steps are application level
  5. 'NOT at the worksheet level as one would expect
  6. '
  7.     zexcelapp.Columns("a:h").Select
  8.     zexcelapp.Selection.ClearContents
  9.     zexcelapp.Range("A1").Select
  10. 'clear the array selection and select the first worksheet in the workbook. 
  11.     Set zexcelsheet = zexcelfile.Worksheets.Item(1)
  12.     zexcelsheet.Select
  13. '
  14. 'and the rest of your code would follow
you need only translate to the xlx and xls and alter the worksheet names as needed.
Take special note of the comment at line 4 in my code!


The code has been tested and works in my ACC2010 test database where in I transferred three queries to a workbook, then selected the information etc...

bol
-Z
May 21 '14 #6
Thanks, much appreciated.
May 21 '14 #7
I'm going on holiday now and won't back until the 2nd of June. Thanks for your help so far, hopefully catch up when I get back. Cheers
May 22 '14 #8

Sign in to post your reply or Sign up for a free account.

Similar topics

3
by: sridevi | last post by:
Hello How to export data from ms-access database to excel worksheet using ASP. mainly i need to export data to multiple worksheets. it is very urgent to us. i have a sample code which works...
1
by: davidgordon | last post by:
Hi, I have a form with 2 combo boxes. I am not using them in the usual way, please read on: In the 'Form Load' event, I have: _______________________________________ dim folderspec as...
3
by: dan_roman | last post by:
Hi, I developed a script with a nice interface in Tkinter that allows me to edit some formulas and to generate an Excel worksheet with VBA macros within it. The script runs perfectlly in Office...
5
by: hmiller | last post by:
Hey there folks: I have been trying to get this work for about a week now. I'm new to VBA... I am trying to transfer a populated table in Access to an existing, but blank, Excel worksheet. I...
0
by: blainegray | last post by:
Greetings This is one of those Access is not closing Excel problems. The first time through the code works fine. The second time there is a problem. After lots of combinations, I finally...
1
by: Haidee | last post by:
Hi I'm pretty new to MS Access so please be patient.... I have a user that is trying to import an external excel spreadsheet into MS access 2003 by using the File - Get external data - Import. ...
5
by: Jakob32 | last post by:
Hi I'm trying to link information from a query in another Access database to my own Access database using this code (which have worked fine for me earlier). SELECT * FROM MinHL IN...
3
by: PW | last post by:
Does the worksheet have to be exported to a CSV file first or can Access import directly from an Excel workbook (.xls)? Thanks, -paulw
1
by: Joe Humburg | last post by:
Hi everyone, Looking for some help or ideas, on the folloiwng problem. Have an Access 2003 application that creates an Excel file containing data from an Access parameter query. This is...
5
by: masoume1 | last post by:
I need to export data, from within a Sql SERVER stored procedure to excel. Right now we use access 2003.The procedure has selected from 2 temporary table which joined with other views in our...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
0
BarryA
by: BarryA | last post by:
What are the essential steps and strategies outlined in the Data Structures and Algorithms (DSA) roadmap for aspiring data scientists? How can individuals effectively utilize this roadmap to progress...
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.