473,408 Members | 2,839 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,408 software developers and data experts.

How do you edit an excel sheet before importing it into access

19
The company i am interning for is having me format data from an excel sheet into a filterable access graph. Im rather new to VBA and at the moment i have a button that imports an excel sheet and re-formats the information to be more fitting to what access likes. I run into an issue however with some of the things that are on the excel sheet side, being that the first 2 rows in all of the sheets are visual fluff and the third row contains what i need for field names. How can i delete the first 2 rows in the excel sheet, without saving it and have it imported into access. The other issue i come across is that the field names, and table names, from the excel sheet have spaces or periods, which from what Ive experienced error wise is a large no in VBA when they are needed to be referenced. So i would also like to know how i can replace all the spaces in the excel sheet with an underscore before importing, again without being saved to the original excel file. Due to being something that is handled by higher ups in the company absolutely none of this can be manual, aside from the button push that starts the code. Access 2007
Jun 19 '17 #1
14 1805
NeoPa
32,556 Expert Mod 16PB
Your last comment is possibly one of the most important and would have been ideal as the first statement. In such circumstances it is critically important that you get a commitment from those dealing with the origination of the files that the formats of these files never change. This is most easily done by explaining, very truthfully, that any code you write will be heavily dependent on finding the data exactly where you expect it. Such code cannot be designed to be flexible without high levels of skill and experience. Thus, your code will work like an automaton. Perfectly fit for the format supplied. Perfectly useless (or worse) for any other.

You will probably guess from my comments that I, as well as many others I've heard from, regularly deal with systems designed for one format of file that are then expected to deal with the file once the format's been changed. It will probably happen for you too. At least if you make a good effort to get those in charge to appreciate the issue there's a chance that will be minimised. On that point make sure you have good notes that you can refer to again when they come back complaining it doesn't work properly any more. Those notes should be somewhere associated with the file itself. Alternatively somewhere you can get to them easily and quickly when the users do come back.

Changing data in an Excel spreadsheet is one thing but importing directly from a spreadsheet into Access from Excel, as opposed to from a file, is probably a lot more complicated than you want to play with at this stage (Unless you're a very ambitious intern with oodles of self-confidence in an area you have no reason to be). Access also tends not to like importing files if they're open, and thus locked, in Excel. I suggest you make your changes and then save them in a new place, before closing the file in Excel, before, in turn, importing the file into Access.

Having read the last comment now, and returned to what I wrote before, I guess this will have to be done in VBA rather than manually. Possible but not basic I'm sorry to say. I would suggest the best place to start is in the VBA of the database you want to import into. This would have to use Application Automation. This allows you to do the work in Excel by getting Access to open Excel and the file before making the changes and saving the changed copy away somewhere else.

You'll see from what I've said that this is going to be a sizeable project. Not something that anyone here should be doing for you. OTOH if you're prepared to take it on then we can certainly assist when the complications confuse or overwhelm you.

I hope you find this helpful.
Jun 19 '17 #2
NeoPa
32,556 Expert Mod 16PB
Let me just add that if your bosses, after realising just how much of a jump into deep water this would be for an intern, do encourage you to proceed with the project, then you could garner some very useful and interesting experience. I suspect you'd enjoy it even if you did get stuck a few times. Probably because you got stuck a few times and managed to get past it. Application Automation is also a very interesting, powerful and useful area. Particularly in office type environments.
Jun 19 '17 #3
HibHib
19
Thank you for the response and for leading me towards what i need to do. Luckily i'm a full time intern with this as my only current project so i have nothing but time to learn. Also luckily, this SHOULD be the last thing i have to do for the project. I will likely be asking for some help as i move further into this step of the project.
Jun 20 '17 #4
NeoPa
32,556 Expert Mod 16PB
I'm happy to hear that HibHib.

To get the best responses break down your problems into small bits and ask each bit separately and clearly. Asking clear questions is tough for most people but the more effort you put into it at that stage the better responses you'll get.

A large number of questions aren't a problem in itself. Links can always be used so that you can keep a lot of the background explanation in your first question.

Good luck.
Jun 20 '17 #5
ADezii
8,834 Expert 8TB
As always, NeoPa offers you a wealth of professional and invaluable advice. I do agree with him in that you have a challenging task ahead of you, but somehow I do get the impression that you can handle it. I also feel that a little Jump Start may be in order and hopefully will be helpful to you. IMHO, the approach to take would be to open the Spreadsheet via Automation Code, make the necessary changes, then Save it under another Filename (in this case Original Base Filename & _2.xlsx). I created a Sample Demo for you that will Open the Spreadsheet, DELETE the first two Rows, then Save it under another Name. It will be this SaveAs File that you would then Import into Access. I have elected to use Early Binding since it is my personal preference. If you are not sure what that is, you can use Google it. Well, here goes. Should you have any questions, we are here to assist you in any way we can.
Expand|Select|Wrap|Line Numbers
  1. Dim strFilePath As String
  2. Dim strWSName As String
  3. Dim appExcel As Excel.Application
  4. Dim wkb As Excel.Workbook
  5. Dim ws As Excel.Worksheet
  6.  
  7. '********** USER DEFINED SECTION **********
  8. strFilePath = "C:\Test\Delete Rows.xlsx"
  9. strWSName = "Sheet1"
  10. '******************************************
  11.  
  12. Set appExcel = New Excel.Application
  13. Set wkb = appExcel.Workbooks.Open(strFilePath)
  14. Set ws = wkb.Worksheets(strWSName)
  15.  
  16. With ws
  17.   .Activate
  18.   .Rows("1:2").Select               'Select Rows 1 and 2
  19.    appExcel.Selection.Delete        'DELETE Rows 1 and 2
  20. End With
  21.  
  22. 'Extract the Base Filename, in this case C:\Test\Delete Rows, then append
  23. '_2.xlsx. Save Delete Rows.xlsx as Delete Rows_2.xlsx
  24. wkb.SaveAs Left$(strFilePath, InStrRev(strFilePath, ".") - 1) & "_2.xlsx"
  25. wkb.Close False
  26. appExcel.Quit
  27.  
  28. Set wkb = Nothing
  29. Set appExcel = Nothing
Jun 20 '17 #6
HibHib
19
Thank you for the example. I *tried* to take your example slightly further but have run into a slight issue. The excel file im using for this project has 12 worksheets/tabs in the same file(all share the exact same layout, it just different values for different months)i tried to set up a loop that would go through each worksheet to delete the first 2 rows in all of them instead of just one. I established a collection of Sheetnames colWorksheets(lngCount) and set that = to strWSName and had it loop based on lngCount. I thought that would work but it only effected the last worksheet in the file and left a bunch of excel files that didn't close. Im assuming this is because i messed up the loop and had it open the excel file multiple times, but i dont know how to fix that
Jun 20 '17 #7
ADezii
8,834 Expert 8TB
I will see what I can do tomorrow - keep in touch. You need to Loop thru the Worksheets Collection of the Workbook Object and Set the Worksheet Object Variable equal to each member prior to each deletion.
Jun 20 '17 #8
NeoPa
32,556 Expert Mod 16PB
Guys.

Please try to avoid stretching a single thread beyond its basic topic.

I can't split this one as it's already too intertwined. Allow the new user to explore and make mistakes. It will help them in the long run.

Feel free to continue helping ADezii, as I know that's who you are, but try to encourage new users to use their own two feet too. We have to ensure we don't stultify their growth by feeding them too much too soon. They can always come back when they get stuck. We're like a safety net rather than a resource to do too much for them.

Bless you for being who you are, but never forget the saying that to teach someone to fish is better than simply giving them some.

@HibHib.
You can learn a lot from ADezii. I'll leave you in his capable hands for now. Obviously I'll continue to monitor and step in if required.
Jun 20 '17 #9
ADezii
8,834 Expert 8TB
  1. NeoPa is of course correct - I have learned more from him then you will ever learn from me. Realizing that I have not exactly made this a learning experience for you up to this point, we can continue along those lines. You have stated that you need to process (DELETE Rows 1 and 2) multiple Worksheets (actual number is irrelevant) within the Workbook. You do not need to create a Private Collection since a Worksheets Collection already exists and it consists of all the Worksheets in the active Workbook. What you need to do now is to set an Object Variable (Worksheet) to each member of this Collection, DELETE Rows 1 and 2, then move on. In its simplest form, within the context of your Code, the Logic would be:
    Expand|Select|Wrap|Line Numbers
    1. '****** CODE INTENTIONALITY OMITTED ******
    2. Dim wsLoop As Excel.Worksheet
    3.  
    4. For Each wsLoop In wkb.Worksheets
    5.   'Process each Worksheet here
    6. Next
    7. '****** CODE INTENTIONALITY OMITTED ******
    8.  
  2. You now need to incorporate what I have shown you into the overall Code.
  3. P.S. - For now forget replacing " " with _ and . with "", once you figure out how to DELETE Rows 1 and 2 from all the Worksheets this will become a relatively simple task.
Jun 21 '17 #10
HibHib
19
I got it to work right! But then i tried to replace " ", which seemed rather straight forward. but no matter what i tried it kept popping up with an error in excel saying "Microsoft Office Excel cannot find any data to replace". Initially i thought it was because it was checking the deleted rows, so i changed it so search row 3 but the same error popped up.
Also, thank you for helping out a newby like me, i know it can get frustrating sometimes
Jun 21 '17 #11
ADezii
8,834 Expert 8TB
  1. Be patient, this is a lot to swallow for a Newbie, especially since you are dealing with Automation Code. IMHO, the easiest approach would be to:
    1. Define a Range Object that will encompass the largest possible Range that will contain Data in the Worksheets.
    2. Use the Replace Method of the Range Object to Replace any Space (" ") with an Underscore (_), then run the Replace operation again to replace any periods (.) with a Zero Length String ("").
    3. This Code needs to applied to each Worksheet Object (within the For Each...Next) after the Deletion of Rows 1 and 2.
    4. The 'Basic' Syntax would be:
      Expand|Select|Wrap|Line Numbers
      1. Range("A1:C25").Replace What:=" ", Replacement:="_", MatchCase:=False
  2. Duplicate this functionality within your Automation Code.
  3. Be patient and persist!
Jun 21 '17 #12
HibHib
19
I actually had that in my code, but with with wsLoop.Rows(1) instead of range because i only needed my fields to have no spaces, my issue was actually a dumb mistake on my part, earlier when i had created a collection, it set the excel sheet to read only, which stopped the replace function from working(Tho oddly not the delete function). Now that that dumb mistake is fixed, the code works! Thank you a ton for the help
Jun 21 '17 #13
ADezii
8,834 Expert 8TB
You are quite welcome, good luck with your Project.
Jun 21 '17 #14
jforbes
1,107 Expert 1GB
I've always seen ADezii's suggestions and code work well, so you could easily continue with what he has provided and know you are going to get what you are asking for and he has provided a method to clean up the spreadsheet, which is exactly what you are asking for.

But I feel that there is another option that should be at least considered.

NeoPa touched on this when he mentioned having Access open Excel an file and modifying it, then saving it, so what I'm proposing isn't entirely unique here.

Another option is within your Access database is to build a function that both cleans up the data as it is being Imported. Both steps are going to happen anyway and as NeoPa mentions this with be an in-depth project. So what I'm suggesting:
  • Is to build a Form in Access that allows you to pick the Excel file, maybe even select the import type if you find you will need to start sucking in multiple Excel files in different formats.
  • When the user hits the Import button, a function is called that opens the Excel and then the Workbook using Automation Objects.
  • Then the routine can parse the Workbook into a set of variables, probably a variable for each column comprising a set for the entire row.
  • It can check the variable and see if they are close to valid.
  • It can check the data in the variables to see what to do ,like skip the line or clear out the variable, or massage the variables so that they are formatted correctly and in the manner that started you on this project.
  • When you have a full set of massaged variable, you can then perform an insert of all the variable into the table you want the values to end up in.
  • You can then perform additional queries on the imported data, like if you were to give each import a batch number, but only need to keep the latest batch, you could then delete all records except the ones with the batch number you just created and imported.
Jun 22 '17 #15

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

Similar topics

2
by: MadCrazyNewbie | last post by:
Hey Group, How could I import a Data from a Excel Spreadsheet, into a Already Exsiting Table, also can I choose which coloum(s) need what row of data in? Many Thanks MCN
7
by: mpdsal | last post by:
Hello. I have some very large text files that I need to import into Access. These files are basically SAP system reports that can be up to 100,000 records but they contain a boatload of data I...
2
by: Patrick B. | last post by:
I have an existing excel spreadsheet that my customers MUST continue using. There are 5 different specially formatted cell groups (tables) on one sheet where the use can enter data. The data in...
6
by: vj83 | last post by:
Hi, I have a C#.net application in which i have read the datas from excel sheet and displayed in a datagrid in my Aspx form. The code is here private void Button2_Click(object sender,...
1
by: cmcl95 | last post by:
HI Folks, I need some help I'm trying to develop a automated way to import from a excel spsh excluding the 1st 2 rows & two out of 41 columns. I got the 1st part with range see below ...
0
Olali
by: Olali | last post by:
Hi, i wanna write code to import a worksheet column into an access table. From there the data inserted is used compared with data in another table to compare a report. Currently i am importing the...
4
by: Elavarasi | last post by:
hi I want to import data from excel sheet to ms access database in asp. sample code if possible regards ela...
1
by: twinkle2010 | last post by:
Hi I am a new web programmer.I got an issue that reads the excel sheet data and store it to MYSQL database using php. I dont have any idea on that. can you help me?
4
by: helplakshmi | last post by:
Hello Everyone, I need to upload excel sheet in to the database. Which i am doing with the query SELECT * INTO temp FROM OPENROWSET('Microsoft.Jet.OLEDB.4.0', 'Excel...
2
by: Syndrogo | last post by:
So i am using a code to export all table data into one excel sheet (http://www.utteraccess.com/forum/index.php?s=&showtopic=1944631&view=findpost&p=1971939) it works fine with exporting the file. I...
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
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...
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
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
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
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

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.