Combine several Excel files into one using VB
I have a folder with several开发者_开发问答 excel files that have a date field, i.e. 08-24-2010-123320564.xls. I want to be able to have some VB scripting that will simply take the files that start with todays date and merge them into one file.
08-24-2010-123320564.xls 08-24-2010-123440735.xls 08-24-2010-131450342.xls
into
08-24-2010.xls
Can someone please help?
Thanks
GabrielVA
assuming you just want to append rows in simple spreadsheets, follow this logic:
- Psuedocode
- use an excel macro
- (you could just as well automate excel from vb but why vbscript alone since you need excel anyway?)
- have it to a dir listing (dir function)
- dim a date_start variable init to "new"
- dim a merged_spreadsheet as new doc default to nothing
- loop thru result of dir
- if date_start <> start of filename
- if merged_spreadsheet is not nothing
- save it
- set it to nothing
- store start of date (left mid function) in date_start
- if merged_spreadsheet is not nothing
- if merged_spreadsheet is nothing
- make a new one
- open the file from the dir command's loop
- select all the data
- copy it
- go to first empty row in merged_spreadsheet
- paste it
- if date_start <> start of filename
- loop files
- if merged_spreadsheet is not nothing
- save it
- use an excel macro
If you're not happy with all those 'nothings', you can set a separate flag to keep track of whether you have a merged_spreadsheet or not. Think about what happens for just one file in a date, no files at all, etc. Of course you will tear out your hair finding out how to automate those excel functions. The secret to turning 'hard' into 'pretty darn easy' is this:
macro recorder will reveal the automation commands
They are not intuitive. So record a macro. Then do things that you'll need to do in your code. Stop recording and look at the result.
For example:
* load/save files
* select only entered fields
* Select all
* copy / switch files / paste
* create new sheet
* click in various single cells and type (how to examine/set a cell's contents)
In summary-
(1) Know exactly the steps to what you're doing
(2) Use macro recorder to give away the secrets of the excel object model. Steal its secrets.
Really this won't be all that hard if you marry these two concepts cleverly. Since the macro will be vbscript (at least if you use office 97 ;-) you can probably run it from vbs or vb6 if you want. A hop to vb.net shouldn't be that hard either.
Aspose makes it pretty easy to work with excel-files in .NET http://www.aspose.com
精彩评论