Page 1 of 4 1234 LastLast
Results 1 to 15 of 53
  1. #1
    Lou_Reed is offline VIP
    Windows 7 64bit Access 2010 64bit
    Join Date
    Mar 2015
    Posts
    1,664

    Generalizing my VBA transfer of an MS Access table to MS Excel

    Is there a way to generalize the transfer of data from an MS Access table to Excel?



    By that I mean not being so specific in the description of the table that is being transferred to Excel.

    I have created a VBA program that is in the attached zipped file that will allow not just a program with four columns to be transferred, but a table much more general in which one does not know how many columns the table has in advance? It could be small number or a large number.

    Right now the VBA code is written for just the table in the db, table 1. It would be great to generalize that so it could take any future table without hard coding
    the specific parameters of that table?

    Any help appreciated. Thanks in advance.

    Respectfully,

    Lou Reed
    Attached Files Attached Files

  2. #2
    John_G is offline VIP
    Windows 7 32bit Access 2010 32bit
    Join Date
    Oct 2011
    Location
    Ottawa, ON (area)
    Posts
    2,615
    Here you are! I tested it, and it works a treat!

    Some changes I made to the way it works:

    - It creates a new worksheet in the Excel file and adds to that, so data won't get overwritten by mistake
    - The field names from the Access table become Column headers in the worksheet (Row 1)

    The name of the table you want to transfer is passed as a parameter to the procedure
    The Excel file name is hard-coded for testing, but you could make it a second parameter of the procedure if you wanted to
    You might want to run it with the Excel window invisible (xl.Visible = False), because you close the spreadsheet at the end of the procedure anyway.

    To run the procedure, just use Test2 "Tablename"
    I think you had it as a button on_click procedure in a form, so you would need to have it take the table name from a form control, but that's a trivial change.

    Code:
    Sub test2(TableName As String)
    Dim xl As Excel.Application
    Set xl = New Excel.Application
    xl.Visible = True
    Dim fld As Field, FieldCount As Integer, J As Integer
    Dim ws As Worksheet
    
    xl.Workbooks.Open ("d:\ms office\MS Excel\testing.xlsx")
    Set ws = xl.ActiveWorkbook.Sheets.Add
    ws.Select
    
    Dim db As DAO.Database, rownum As Long
    Set db = CurrentDb
    
    Dim rs As DAO.Recordset
    Set rs = db.OpenRecordset(TableName)
    rownum = 1
    
    rs.MoveFirst
    
    '
    ' Fieldcount contains the number of fields in the recordset
    '
    FieldCount = rs.Fields.Count
    
    '
    ' first row of the spreadsheet contains the fieldnames, making it a header row
    '
    For J = 1 To FieldCount
      ws.Cells(rownum, J).Value = rs.Fields(J - 1).Name   ' Use j-1 because recordset field index is zero-based
    Next J
    '
    ' Now copy the data from the recordset to the Excel spreadsheet rows 2...
    '
    Do While Not rs.EOF
      rownum = rownum + 1
      For J = 1 To FieldCount
        ws.Cells(rownum, J).Value = rs.Fields(J - 1).Value   ' Use j-1 because recordset field index is zero-based
      Next J
      
    rs.MoveNext
    Loop
    xl.ActiveWorkbook.Close (True)
    xl.Quit
    
    End Sub

  3. #3
    Lou_Reed is offline VIP
    Windows 7 64bit Access 2010 64bit
    Join Date
    Mar 2015
    Posts
    1,664
    In the zipped included in this past is my db with the generalized code in it. It is the second export to Excel button. It failed on the line

    Set rs = db.Openrecordset(tableName)

    Please notice the capitalization of the name tableName. It reflects the best that I can do in setting up the code.

    If I put in the word TableName it rewrites it to tableName and then the lines causes the compile
    to fail. I am not sure why it will not let me write the name the way that I want it. I want it
    as TableName and I cannot be sure that is what is causing the compile to fail on this line.

    Also, a second question about accessing the files. One is the db, tablename and other is for the Excel file that is gets the imported MS Access file.

    I like to make things user friendly.

    I hoping to use the browse method; but I think that will work in only one situation. The browse method assumes the Excel files exists and it only exists if I set it up to before the export of the Access
    table to the Excel software.

    It must be setup that a way because the first line in the table and hence the first line in the Excel spreadsheet contain the column names.

    I do not know how to program that into to the VBA code, it seems unnecessary since I can set up a spreadsheet with the first row containing only column names and simply copy it over and over.

    It seems lot easier than trying to program that into the VBA code.

    I just was to make the user experience as pleasant as possible and it seems that a browse box is one way to get the Excel spreadsheet file.

    Finally, is there a way to put in the TableName in the program on the same line as the computer prompt?

    It seems more user friendly that way.

    Any help appreciated. Thanks in advance.

    Respectfully,

    Lou Reed
    Attached Files Attached Files

  4. #4
    John_G is offline VIP
    Windows 7 32bit Access 2010 32bit
    Join Date
    Oct 2011
    Location
    Ottawa, ON (area)
    Posts
    2,615
    Lou, would you please read what I post before posting about additional errors!

    You pasted in the code fine, and you changed the name of the Excel file OK, but you ignored this:

    I think you had it as a button on_click procedure in a form, so you would need to have it take the table name from a form control, but that's a trivial change.

    Your compile fails in this line : Set rs = db.OpenRecordset(tableName) because it doesn't know what tableName is - you get a "Variable not defined" error.

    I am not sure why it will not let me write the name the way that I want it. I want it
    as TableName and I cannot be sure that is what is causing the compile to fail on this line.
    Whether you write it as TableName or tableName means nothing to Access. To Access they are the same thing, and it still doesn't know what it is.
    I think it changes it to tableName because you use it that way elsewhere in your code, so I suppose Access thinks that what it should be.

    If you want to try the code to see if it works in the button On_Click code, change TableName to the actual name of one of your tables (in quotes), run it, then have a look at the Excel spreadsheet to see the result.

    The browse method assumes the Excel files exists
    That's correct, but you can set set things up so that the procedure creates a new excel file instead of opening an existing one.

    ...first line in the table ... contain the column names.
    No. The field names in an Access table are part of the table structure, and are not contained in a table record. However, as I showed you, they can be read from the recordset field properties.

    I do not know how to program that into to the VBA code,
    I did that for you:

    Code:
    '
    ' FieldCount contains the number of fileds in the recordset
    '
    FieldCount = rs.Fields.Count
    '
    ' first row of the spreadsheet contains he fieldnames, making it a header row
    '
    For J = 1 To FieldCount
      ws.Cells(rownum, J).Value = rs.Fields(J - 1).Name   'Use j-1 because recordset field index is zero-based
    Next J
    I can set up a spreadsheet with the first row containing only column names and simply copy it over and over.
    Yes, but then it's not generalized for any table.

    Finally, is there a way to put in the TableName in the program on the same line as the computer prompt?
    What do you mean by "computer prompt" here - the icon to start Access? But why would you? Don't you want the procedure to be general for any table - putting it on the start prompt means you would have to change it each time.

  5. #5
    Lou_Reed is offline VIP
    Windows 7 64bit Access 2010 64bit
    Join Date
    Mar 2015
    Posts
    1,664
    So I believe the first thing that I must do is to turn off AutoCorrrect in MS Access. If it is on that would explain why when I write TableName it changes it to tableName.

    Thanks very much for your help on other parts of the code.

    Respectfully,

    Lou Reed

  6. #6
    Lou_Reed is offline VIP
    Windows 7 64bit Access 2010 64bit
    Join Date
    Mar 2015
    Posts
    1,664
    I do not know to to set up a form too take table name. I was able to do many similar things, but that one I do not know how to do. it just seems a bit tacky to hard code the table name. Is there a reference
    on how to do this.

    Also, you said that I can set up a procedure that creates a new Excel file. Not just lets you select an existing file from a many in a directory. How do you do that? Also, please understand that my Excel file has several rows for columns titles. I hope to preserve that in any newly created file.

    So it must be able to create a new Excel file, but also to include (and I am not sure how) these changes that I outlined in a previous sentence.

    Any help appreciated. Thanks in advance.

    Respectfully,


    Lou Reed

  7. #7
    Lou_Reed is offline VIP
    Windows 7 64bit Access 2010 64bit
    Join Date
    Mar 2015
    Posts
    1,664
    I am stuck. I can export a MS Access table to MS Excel, but I cannot set it up so I can choose the table. I must hardcode the table name in. I cannot just select the table name from a list. How do I set this up so it can work?

    Any help appreciated. Thanks in advance.

    Respectfully,

    Lou Reed

  8. #8
    Lou_Reed is offline VIP
    Windows 7 64bit Access 2010 64bit
    Join Date
    Mar 2015
    Posts
    1,664
    Okay, I think that I know how to do it. But doing and just knowing how to do it are two different things.

    The first part is that I must make a query to list all of the tables in a db.

    Something like

    SELECT [Name]
    FROM MySysObjects
    WHERE Type In (1,4,6)
    AND Left ([Name], .4) <> "MSys"
    ORDER BY [Name]

    The put the name of the sql code as a row source to a combo box, with the type as a value list.

    Now from there I am lost because I want the selection from the combo box to be
    set to a variable and that variable goes to the VBA line:

    Set rs = db.OpenRecordset(TableName)

    Where TableName is the selection, I set to the to value (TableName) that I chose
    in the combo box.

    I believe this is the way to do it. I am sure that there are otherways.

    Now I am a little nervous about unhiding the files into order
    to perform the SQL line

    SELECT [Name]
    FROM MSysObjects


    I know how to do it. In fact, I know two ways to do it. But I do not want to
    alter anything in the system files. That is the part that concerns me.

    So the question is this the correct way to do it, and if so how to avoid altering
    system files? There are many warnings about this in the various MS Access SQL
    programming books.

    Any help appreciated. Thanks in advance.

    Respectfully,

    Lou Reed

  9. #9
    Lou_Reed is offline VIP
    Windows 7 64bit Access 2010 64bit
    Join Date
    Mar 2015
    Posts
    1,664
    In the zip file that I uploaded is a database that has the query List Tables in it. To run this query I unhid the system tables.

    The database query list tables does not run correctly. It should list the table. it does not.

    What is wrong here?

    Any help appreciated. thanks in advance.

    Respectfully,


    Lou Reed
    Attached Files Attached Files

  10. #10
    John_G is offline VIP
    Windows 7 32bit Access 2010 32bit
    Join Date
    Oct 2011
    Location
    Ottawa, ON (area)
    Posts
    2,615
    So I believe the first thing that I must do is to turn off AutoCorrrect in MS Access. If it is on that would explain why when I write TableName it changes it to tableName.
    I don't think that will work - it's not what Autocorrect is for, and it doesn't apply to VBA. From what I can find out, this behaviour of VBA, to change the case of names, can't be turned off. Besides, if Access VBA keeps changing something you type, it almost always means you have made a mistake somewhere, often not using a Dim for the variable in question. I have found if I use Capitals or MixedMode when naming objects (form controls, table fields, Sub and Function names, VBA variable names), and then writing VBA code only in lower case, it will catch a lot of mistakes, because Access won't change the capitalization.

    In you case, when Access insists on changing TableName to Tablename, it is because you have used Tablename somewhere in your database, and you have not redeclared it in the current sub with Dim TableName as String.

    Not just lets you select an existing file from a many in a directory. How do you do that? Also, please understand that my Excel file has several rows for columns titles. I hope to preserve that in any newly created file.
    Yes, I see your point. Formatting the Excel file headers as you want them is very definitely doable in VBA, but it is a bit of a pain to get it right, and requires running the code many times (from experience!). However, that brings up another question - if you already have the headers, or know what you want them to be, then your process is no longer general for any table - only tables with the proper design will fit the Excel layout. You can't have it both ways.

    However, what you can do is make a copy of the Excel spreadsheet with all the proper headers which you can use as a template. Your Access code can open that template file and when it has filled in the data, it does a Save As instead of a Save, so that it does not overwrite the template. You would determine the file name that the Save As would use.

    I cannot set it up so I can choose the table. I must hardcode the table name in. I cannot just select the table name from a list.
    Actually you can. You create a listbox and populate its choices with the list of table names; an explanation and some sample code to do that are here:
    https://bytes.com/topic/access/answe...-names-listbox

    Then, once you have selected a table name, you just pass that name to your export procedure as a parameter, or have the export procedure look at the list box for the name that was selected.

    But I do not want to alter anything in the system files.
    Not to worry. As long as you are just using the system files in a Select query, no harm can be done. And, if you check the link I showed you above, you can populate the list or combo box without accessing the system files directly.

    I want the selection from the combo box to be set to a variable and that variable goes to the VBA line:

    Set rs = db.OpenRecordset(TableName)
    The easiest way there is to not use an intermediate variable, and just reference the combo box itself:
    Set rs = db.OpenRecordset(me!comboboxname)

    Or, if you do want to use a variable:

    TableName = me!comboboxname
    Set rs = db.OpenRecordset(TableName)

  11. #11
    Lou_Reed is offline VIP
    Windows 7 64bit Access 2010 64bit
    Join Date
    Mar 2015
    Posts
    1,664
    The link that you gave me, in your last post, I cannot get to. You got to love US Gov. computers.
    Now as for using a file in Excel with all the headers added but with no data (use as a template), I suggested that in a earlier post.

    It was shot down.

    In my post just before this one, I attached a zipped file that contained a query that should list all the tables in the db; there are three.

    Now they are put into a combo box. I explained how in an earlier post.

    Then you explained how to get that selection from a combo box and put in VBA code for the exporting an MS Access table.

    I just cannot get the code the work in the List Tables Query.

    What is up with that.

    Any help appreciated. Thanks in advance.

    Respectfully,

    Lou Reed

  12. #12
    John_G is offline VIP
    Windows 7 32bit Access 2010 32bit
    Join Date
    Oct 2011
    Location
    Ottawa, ON (area)
    Posts
    2,615
    The database query list tables does not run correctly. It should list the table. it does not.
    The criteria under "type" should be 1, not 6.

    You should also filter out the system table names with this in the criteria for "Name": Left([name],4)<>"msys"



  13. #13
    Lou_Reed is offline VIP
    Windows 7 64bit Access 2010 64bit
    Join Date
    Mar 2015
    Posts
    1,664
    Okay, but when I ran it I got nothing as a response. The criteria, but not the filter I assume were working.

    I just got zip.

    What is up with that?

    I will make your changes.

    Respectfully,

    Lou Reed

  14. #14
    Lou_Reed is offline VIP
    Windows 7 64bit Access 2010 64bit
    Join Date
    Mar 2015
    Posts
    1,664
    I modified the SQL code and the query does run. But it does not filter out the system files names. As you can see, I did put that line (to filter out sys names) in.

    I do not understand what I did wrong. I do think that I am filtering out the system files, but apparently not.

    Any help appreciated. Thanks in advance.


    Respectfully,

    Lou ReeD
    Attached Files Attached Files

  15. #15
    Lou_Reed is offline VIP
    Windows 7 64bit Access 2010 64bit
    Join Date
    Mar 2015
    Posts
    1,664
    Okay, I have got this one. I did not spell MSys correctly in my SQL code.

    However, I still have a question on the issue. I can make as election from the list box, but I think it would be better to integrate
    the SQL code into the VBA code and then use the listbox selection in the remaining part of the code.

    Wouldn't that do it?

    Any help appreciated. thanks in advance.

    Respectfully,


    Lou Reed

Page 1 of 4 1234 LastLast
Please reply to this thread with any new information or opinions.

Similar Threads

  1. Replies: 1
    Last Post: 04-17-2016, 02:33 PM
  2. Automatic transfer data from Access to Excel
    By Sarabjit in forum Access
    Replies: 11
    Last Post: 10-20-2014, 07:27 PM
  3. Replies: 5
    Last Post: 06-12-2011, 03:58 PM
  4. How to transfer data from excel to Access?
    By mit in forum Import/Export Data
    Replies: 4
    Last Post: 06-11-2011, 05:39 PM
  5. Transfer Access into Excel problem
    By BorisGomel in forum Programming
    Replies: 4
    Last Post: 05-23-2011, 02:47 PM

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
Other Forums: Microsoft Office Forums