473,379 Members | 1,379 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,379 software developers and data experts.

Exporting a report to Excel and formatting it with Access VBA

I am creating a form that selects data based on a user selected model type, flange type, and a range of line sizes. This hasn't been a problem, I am able to get the correct report from the form thus far.

My issue is the button I am using to export the report to excel. I want the button to save the file with a filename based on the parameters selected in the form, then open the excel file, delete empty columns, move the table a bit (just so the borders are visible), and then add the lines to make it look like a nice table. I am at the point where this works most of the time when I click the button. It seems to be not working properly whenever excel is already open, especially if there is an excel file that is already open which was created by this button. What really gets me is that it'll give a "Method 'Range' of object '_Global' " error sometimes but if I close the excel file and try again it will work no problem.

Keep in mind that I am a complete novice when it comes to Access and VBA in general - everything you see here I have taught myself in the last week. So feel free to treat me like a child, I am learning each step of the way.

I have omitted all the code concerning the option lists on the form. This is just the button.

Expand|Select|Wrap|Line Numbers
  1. Option Compare Database
  2. Option Explicit
  3.  
  4. Private objExcel As Excel.Application
  5. Private xlwb As Excel.Workbook
  6. Private xlws As Excel.Worksheet
  7.  
  8. Private Sub CreateTable_Click()
  9.  
  10. Dim filename As String
  11. Dim lastrow As Long
  12. Dim lastcolumn As Long
  13. Dim i As Long
  14. Dim flange As String
  15.  
  16. Select Case FlangeType.Value
  17. Case 1
  18. flange = "SO"
  19. Case 2
  20. flange = "WN"
  21. Case 3
  22. flange = "WA"
  23. End Select
  24.  
  25. 'set filename based on filter of table and save as excel sheet
  26. filename = "Type1drawing_" & DrawingType.Value & "_" & flange & "flange_" & minsize.Value & "_to_" & maxsize.Value & ".xls"
  27.     DoCmd.OutputTo acOutputReport, "rptType1Drawing", "Excel97-Excel2003Workbook(*.xls)", filename, False, "", 0, acExportQualityPrint
  28.  
  29. 'set an excel object and open the saved file to format correctly
  30.   Set objExcel = New Excel.Application
  31.   objExcel.Visible = True
  32.   Set xlwb = objExcel.Workbooks.Open(filename)
  33.   Set xlws = objExcel.Worksheets("Type 1 Drawing Maker")
  34.  
  35.   objExcel.ScreenUpdating = False
  36.   objExcel.Calculation = xlCalculationManual
  37.   xlws.Activate
  38.  
  39. With xlws
  40. lastrow = Range("A1").End(xlDown).Row
  41. lastcolumn = Range("A1").End(xlToRight).Column
  42. i = lastcolumn
  43.  
  44.     'delete empty columns (non-available liners)
  45.     Do Until i = 0
  46.     If WorksheetFunction.CountA(Range(Cells(2, i), Cells(lastrow, i))) = 0 Then 'use row 2 so the headers aren't counted
  47.     Columns(i).Delete
  48.     End If
  49.     i = i - 1
  50.     Loop
  51.     'move for better view and then format
  52.     Range("A1", Cells(lastrow, lastcolumn)).Cut
  53.     Range("b2").Select
  54.     ActiveSheet.Paste
  55.  
  56.  
  57.  'update the last column and row
  58. lastcolumn = Range("b2").End(xlToRight).Column
  59. lastrow = Range("b2").End(xlDown).Row
  60.  
  61.     Range("b2", Cells(lastrow, lastcolumn)).Select
  62.     Selection.Borders(xlDiagonalDown).LineStyle = xlNone
  63.     Selection.Borders(xlDiagonalUp).LineStyle = xlNone
  64.     With Selection.Borders(xlEdgeLeft)
  65.         .LineStyle = xlContinuous
  66.         .Weight = xlThin
  67.         .ColorIndex = xlAutomatic
  68.     End With
  69.     With Selection.Borders(xlEdgeTop)
  70.         .LineStyle = xlContinuous
  71.         .Weight = xlThin
  72.         .ColorIndex = xlAutomatic
  73.     End With
  74.     With Selection.Borders(xlEdgeBottom)
  75.         .LineStyle = xlContinuous
  76.         .Weight = xlThin
  77.         .ColorIndex = xlAutomatic
  78.     End With
  79.     With Selection.Borders(xlEdgeRight)
  80.         .LineStyle = xlContinuous
  81.         .Weight = xlThin
  82.         .ColorIndex = xlAutomatic
  83.     End With
  84.     With Selection.Borders(xlInsideVertical)
  85.         .LineStyle = xlContinuous
  86.         .Weight = xlThin
  87.         .ColorIndex = xlAutomatic
  88.     End With
  89.     With Selection.Borders(xlInsideHorizontal)
  90.         .LineStyle = xlContinuous
  91.         .Weight = xlThin
  92.         .ColorIndex = xlAutomatic
  93.     End With
  94.     With Selection
  95.         .RowHeight = 14
  96.         .VerticalAlignment = xlCenter
  97.     End With
  98.     With Selection.Font
  99.         .ColorIndex = xlAutomatic
  100.         .TintAndShade = 0
  101.     End With
  102.     Columns.AutoFit
  103.     Cells(1, 1).Select
  104.     End With
  105.  
  106.  
  107. objExcel.ScreenUpdating = True
  108. objExcel.Calculation = xlCalculationAutomatic
  109. xlwb.Save
  110. Set objExcel = Nothing
  111. Set xlwb = Nothing
  112. Set xlws = Nothing
  113.  
  114. End Sub
  115.  
Jul 23 '14 #1

✓ answered by MikeTheBike

Hi

When automaton Excel (or any office application) in Access etc you need to explicitly refer to the Excel object because, If you do not, then the application running he code makes assumption as ti what you are referring to, which is not good.

I am a bit surprised this work at all, but i have had a similar experience with Word in my 'younger' days.

In your code you do not qualify any range or cell object so access will not now you have opened a new file and assume it is the original file (I think). There is a certain amount of supposition in these comments. However if you use explicit references then there is no ambiguity and the program knows exactly what you indended.

So, below I have moded a part of you code to indicate how I would do this
Expand|Select|Wrap|Line Numbers
  1. With xlws
  2.     lastrow = .Range("A1").End(xlDown).Row
  3.     lastcolumn = .Range("A1").End(xlToRight).Column
  4.     i = lastcolumn
  5.  
  6.     'delete empty columns (non-available liners)
  7.     Do Until i = 0
  8.         If objExcel.WorksheetFunction.CountA(.Range(.Cells(2, i), .Cells(lastrow, i))) = 0 Then 'use row 2 so the headers aren't counted
  9.         .Columns(i).Delete
  10.     End If
  11.     i = i - 1
  12.     Loop
  13.     'move for better view and then format
  14.     .Range("A1", xlws.Cells(lastrow, lastcolumn)).Cut
  15.     .Range("b2").Select
  16.     .Paste
  17.  
  18.  
  19.     'update the last column and row
  20.     lastcolumn = .Range("b2").End(xlToRight).Column
  21.     lastrow = .Range("b2").End(xlDown).Row
  22.  
  23.     'FORMAT RANGE
  24.     With .Range("b2", .Cells(lastrow, lastcolumn))
  25.         .RowHeight = 14
  26.         .VerticalAlignment = xlCenter
  27.         .Borders(xlDiagonalDown).LineStyle = xlNone
  28.         .Borders(xlDiagonalUp).LineStyle = xlNone
  29.         With .Borders(xlEdgeLeft)
  30.             .LineStyle = xlContinuous
  31.             .Weight = xlThin
  32.             .ColorIndex = xlAutomatic
  33.         End With
  34.         With .Borders(xlEdgeTop)
  35.             .LineStyle = xlContinuous
  36.             .Weight = xlThin
  37.             .ColorIndex = xlAutomatic
  38.         End With
  39.         With .Borders(xlEdgeBottom)
  40.             .LineStyle = xlContinuous
  41.             .Weight = xlThin
  42.             .ColorIndex = xlAutomatic
  43.         End With
  44.         With .Borders(xlEdgeRight)
  45.             .LineStyle = xlContinuous
  46.             .Weight = xlThin
  47.             .ColorIndex = xlAutomatic
  48.         End With
  49.         With .Borders(xlInsideVertical)
  50.             .LineStyle = xlContinuous
  51.             .Weight = xlThin
  52.             .ColorIndex = xlAutomatic
  53.         End With
  54.         With .Borders(xlInsideHorizontal)
  55.             .LineStyle = xlContinuous
  56.             .Weight = xlThin
  57.             .ColorIndex = xlAutomatic
  58.         End With
  59.         With .Font
  60.             .ColorIndex = xlAutomatic
  61.             .TintAndShade = 0
  62.         End With
  63.     End With
  64.  
  65.     .Columns.AutoFit
  66.     .Cells(1, 1).Select
  67. End With
  68.  
In short, in this code block, every time you use the Range or Cell obects you need a period/full stop in front of it.
You will note I have remove all reference to the 'With Selection' and used 'With .Range("b2", .Cells(lastrow, lastcolumn))' directly as you do not deed to select the range to refer to it.

Note, I also think the 'WorksheetFunction' if a part of the application object ie. objExcel in this case.

As I have/cannot run the code I may have missed some object referrals.


HTH

12 4852
Rabbit
12,516 Expert Mod 8TB
You could create a "template" workbook with all your formatting already done. Then make a copy of the workbook and import the data into it. That way you don't have to code all the formatting work and makes it easier to change formatting later down the road.
Jul 23 '14 #2
The issue is that I will not be the only perosn accessing this database. So the code needs to produce the Excel sheet in the correct format from any computer that has Excel and Access on it. So the Access VBA needs to complete the entire task if I'm not mistaken.
Jul 23 '14 #3
Rabbit
12,516 Expert Mod 8TB
Can you not put the excel template in a central network location that everyone has access to? Or include the excel template with each person's copy of the Access database?
Jul 23 '14 #4
I don't know, I'm just a summer intern. I suppose that is probably possible but shouldn't it be possible to get Access VBA to control Excel anyways?
Jul 23 '14 #5
Rabbit
12,516 Expert Mod 8TB
It's possible, it's just way more complicated. You can refer to this article if you want to go that route: http://bytes.com/topic/access/insigh...ion-automation
Jul 23 '14 #6
NeoPa
32,556 Expert Mod 16PB
I just deleted your question in the article thread. It's a perfectly valid question - but article threads aren't there for asking questions in.

If you repeat it here I will see it and can respond. Alternatively, you can post it in a new thread if you prefer. I'm more likely to see it from in here though ;-)

Strangely, one of my first ever tasks myself in Access was to produce a procedure called "Prettify()" which basically did a similar job to what you're asking about. That was a few years ago now mind.
Jul 24 '14 #7
Well the question basically pertained to the one this thread is about. I don't quite understand what part of this code is not properly referencing excel.
Jul 24 '14 #8
MikeTheBike
639 Expert 512MB
Hi

When automaton Excel (or any office application) in Access etc you need to explicitly refer to the Excel object because, If you do not, then the application running he code makes assumption as ti what you are referring to, which is not good.

I am a bit surprised this work at all, but i have had a similar experience with Word in my 'younger' days.

In your code you do not qualify any range or cell object so access will not now you have opened a new file and assume it is the original file (I think). There is a certain amount of supposition in these comments. However if you use explicit references then there is no ambiguity and the program knows exactly what you indended.

So, below I have moded a part of you code to indicate how I would do this
Expand|Select|Wrap|Line Numbers
  1. With xlws
  2.     lastrow = .Range("A1").End(xlDown).Row
  3.     lastcolumn = .Range("A1").End(xlToRight).Column
  4.     i = lastcolumn
  5.  
  6.     'delete empty columns (non-available liners)
  7.     Do Until i = 0
  8.         If objExcel.WorksheetFunction.CountA(.Range(.Cells(2, i), .Cells(lastrow, i))) = 0 Then 'use row 2 so the headers aren't counted
  9.         .Columns(i).Delete
  10.     End If
  11.     i = i - 1
  12.     Loop
  13.     'move for better view and then format
  14.     .Range("A1", xlws.Cells(lastrow, lastcolumn)).Cut
  15.     .Range("b2").Select
  16.     .Paste
  17.  
  18.  
  19.     'update the last column and row
  20.     lastcolumn = .Range("b2").End(xlToRight).Column
  21.     lastrow = .Range("b2").End(xlDown).Row
  22.  
  23.     'FORMAT RANGE
  24.     With .Range("b2", .Cells(lastrow, lastcolumn))
  25.         .RowHeight = 14
  26.         .VerticalAlignment = xlCenter
  27.         .Borders(xlDiagonalDown).LineStyle = xlNone
  28.         .Borders(xlDiagonalUp).LineStyle = xlNone
  29.         With .Borders(xlEdgeLeft)
  30.             .LineStyle = xlContinuous
  31.             .Weight = xlThin
  32.             .ColorIndex = xlAutomatic
  33.         End With
  34.         With .Borders(xlEdgeTop)
  35.             .LineStyle = xlContinuous
  36.             .Weight = xlThin
  37.             .ColorIndex = xlAutomatic
  38.         End With
  39.         With .Borders(xlEdgeBottom)
  40.             .LineStyle = xlContinuous
  41.             .Weight = xlThin
  42.             .ColorIndex = xlAutomatic
  43.         End With
  44.         With .Borders(xlEdgeRight)
  45.             .LineStyle = xlContinuous
  46.             .Weight = xlThin
  47.             .ColorIndex = xlAutomatic
  48.         End With
  49.         With .Borders(xlInsideVertical)
  50.             .LineStyle = xlContinuous
  51.             .Weight = xlThin
  52.             .ColorIndex = xlAutomatic
  53.         End With
  54.         With .Borders(xlInsideHorizontal)
  55.             .LineStyle = xlContinuous
  56.             .Weight = xlThin
  57.             .ColorIndex = xlAutomatic
  58.         End With
  59.         With .Font
  60.             .ColorIndex = xlAutomatic
  61.             .TintAndShade = 0
  62.         End With
  63.     End With
  64.  
  65.     .Columns.AutoFit
  66.     .Cells(1, 1).Select
  67. End With
  68.  
In short, in this code block, every time you use the Range or Cell obects you need a period/full stop in front of it.
You will note I have remove all reference to the 'With Selection' and used 'With .Range("b2", .Cells(lastrow, lastcolumn))' directly as you do not deed to select the range to refer to it.

Note, I also think the 'WorksheetFunction' if a part of the application object ie. objExcel in this case.

As I have/cannot run the code I may have missed some object referrals.


HTH
Jul 24 '14 #9
This seems to have fixed my problem of using the button two times in a row. Thank you, I didn't realize that putting a "." infront of everything was necessary. Live and learn!
Jul 24 '14 #10
NeoPa
32,556 Expert Mod 16PB
ghallan:
I didn't realize that putting a "." infront of everything was necessary.
This is related to using With in your code. generally a good idea and very much to be recommended.

ghallan:
I don't quite understand what part of this code is not properly referencing excel.
Well, you have to do a bit of work on that yourself first. Just dumping code (114 lines) for others to scan through and find your problems without any clues isn't a great idea. None of us has the code in a working project so that would be many times more work for others than the basics would be for you.

Start by determining what is failing where in your code. Identify which reference isn't working as expected. Error messages and line numbers are important here. When you have that very basic information then ask a specific question related to that and we'll do what we can to help you.

You may no longer need the help for this question, but please remember the idea for your next ones. It will make it much easier to provide you with a quicker, and more helpful, response.
Jul 25 '14 #11
MikeTheBike
639 Expert 512MB
Hi again

Just a little more info on this subject.
I indicated my surprise that this code work at all.

It has now dawned on me that your code used early binding with a reference to the Excel library; therefore the compiler would eventually fine the object and methods after first searching the Access library.

I always use late binding (to eliminate DLL problems in different version of Office) which does not have a reference to the Excel library, in which case it would not have compiled as it was, and explicit references to the object variables would be required at all times as indicated.

The first time your code runs it assigns the unqualified objects to the first file, but this assignment is not changed in subsequently passes and is still looking for this first file, which is closed or not the active file/worksheet, I think.

So, as NeoPa said, it is always best, when using automation, to reference the objects/methods explicitly.

Hope that help.

MTB
Jul 25 '14 #12
Thanks guys. This is my first time using VBA for a project and my first time using a website like this for help. All the pointers are greatly appreciated.
Jul 25 '14 #13

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

Similar topics

0
by: Ali Eghtebas | last post by:
Hi, I tried this demo application in here (watch for any line breaks in the URL): (http://support.crystaldecisions.com/communityCS/FilesAndUpdates/vbnet_win_a dodotnet.exe.asp When exporting...
3
by: Paul | last post by:
I have written code to transfer a table to an Excel document. However, I do not know the code to add some "bells and whistles" to the document. Can someone direct me to a reference on the Internet...
5
by: mik18 | last post by:
I'm having trouble with exporting reports to Word in the rtf format and I'm hoping someone has a solution. The reports are losing their formats. Not all the formating is lost but some is and of...
1
by: Mustufa Baig | last post by:
I have an ASP.NET website where I am showing off crystal reports to users by exporting them to pdf format. Following is the code: ---------------- 1 Private Sub ExportReport() 2 Dim oStream...
6
by: jpatchak | last post by:
Hi, I have kind of a strange problem. I have a report that I need to export to excel. The report opens fine in Access and when I export it or click on "Analyze It with Microsoft Office Excel," I...
1
by: Kathy | last post by:
I have a number of reports in a MS Access application that have a logo picture embedded in the report. When I run the report and choose File, then Export to Excel, I get an error indicating...
5
by: Roo06 | last post by:
I am trying to open a spreadsheet from Acess based on a value in a textbox. I don't how to create the reference to the path and file name and was wondering if someone could help. I am new to VBA and...
3
by: jennwilson | last post by:
Access 2000 - I have developed a database that houses patient information. The patient information must be sent in an excel file to another company department. I know how to export my data to Excel...
3
by: Tempalli | last post by:
I am exporting the data from ms access to excel where the error displays as Run-time error -2147467259(800004005) Method 'Copyfromrecordset' of object 'Range' faild. ...
4
by: colintis | last post by:
Before asking the question I've been digging a hole that is deep enough to bury myself in google....Most of the results are simply importing the excel file to table with the same table structure. ...
0
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 3 Apr 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome former...
0
by: ryjfgjl | last post by:
In our work, we often need to import Excel data into databases (such as MySQL, SQL Server, Oracle) for data analysis and processing. Usually, we use database tools like Navicat or the Excel import...
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...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...

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.