Modify Excel File and save as CSV using vba - vba

I am working on populating a new application full of resident data. I have to export a list of residents for each property. Unfortunatly the new application has to have the residents imported 1 property at a time. This means im stuck loading 200+ properties by exporting an excel file, slightly modifing the data and then importing into the new application.
For each property that is exported I must remove a '-' from the first column and i have to remove all of the ',' throughout the entire document. I then change the formating on a date column to 'mm/dd/yyyy'. Then the document is saved as a CSV and can be imported.
I would like to write a script that can perform the updates to the excel file and save it to a csv. Please advise if this is worth my time. This is a one time load so it might be better to just power through.
Thank You

Possibly a little prematurely, as I'm not certain this is what you want to achieve, but you could try this (save first):
Sub replaceStuff()
ActiveSheet.Range("A:A").Replace "-", ""
ActiveSheet.Cells.Replace ",", ""
ThisWorkbook.SaveAs "doc", xlCSVWindows
End Sub

Related

Access Data From Already Open But Not Saved Excel File In Separate Instance

I have two excel files in separate instances of excel. I want to take data from one instance of excel to another. This seemed simple as I know that path of the file that I want to pull data from. However, the file I want to pull data from is used by a separate program where it opens up the file I want to pull from (a template), populates it, but does not save it. So each time this external program is running it is using the file I want to pull data from but since it never saves it I am having a hard time pulling data from the template file. I have used the getObject() function which successfully pulls data from the file as I know the file path but the fields are of course empty as when the external program used the file, it only filled in the data but never saves it. How can I do what I am asking?
Building on Scotts suggestion
Since you know the full path and name of the other workbook, use GetObject to reference it
Use .SaveCopyAs to save it
Open the saved copy in the local instance
This code goes in the file running in your instance of Excel
Sub Demo()
Dim wbRemote As Workbook
Dim wbLocal as Workbook
' Get reference to the workbook running in the other instance of Excel
Set wbRemote = GetObject("C:\data\Temp\TemplateBook.xlsx")
' Save a copy
wbRemote.SaveCopyAs "C:\data\Temp\Temp.xlsx"
' remove reference
Set wbRemote = Nothing
' open copy in this instance
Set wbLocal = Application.Workbooks.Open("C:\data\Temp\Temp.xlsx")
' work with object wbLocal
' ...
End Sub

Export Access Query WITHOUT Formatting

Relatively simple, but I can't seem to work it out. I want to export a query from access into a .csv (tab or comma delimited). When I do it manually through the wizard it works fine. But when I do it via vba, it comes complete with dash formatting that looks like the borders in the table!
I tried two methods and got the same results
DoCmd.OutputTo acOutputQuery, "Qry_GRADE", "MS-DOSText(*.txt)",_
"grade.csv", True, *ExportSpec*, , acExportQualityScreen
I used it with or without "ExportSpec", which is a specification I created when exporting manually.
This is the second method:
Dim testSQL As String
Dim qd As DAO.QueryDef
testSQL = "SELECT * FROM Qry_Grade"
Set qd = db.CreateQueryDef("tmpExport", testSQL)
DoCmd.TransferText acExportDelim, , "tmpExport",_
"C:\Users\Databoe\Documents\KidsTV\grade.csv"
db.QueryDefs.Delete "tmpExport"
This is a solution I've found which seems like overkill
And this is what the output looks like:
You can see it's not actually split any of the columns when opening the file in excel and that every second line is just a string of "-"'s
What about DoCmd.TransferSpreadsheet acExport, acSpreadsheetTypeExcel9, myQueryName, myExportFileName, True for direct excel file export.
I tried your approaches, but I only get formated text with your first try DoCmd.OutputTo acOutputQuery, "Qry_GRADE", "MS-DOSText(*.txt)",_
"grade.csv", True, *ExportSpec*, , acExportQualityScreen which is as expected because it's a text export not csv.
With your second method I always get an excel compatible result. Maybe you have an error trap that hides an error and the first grade.csv is not overwritten. Use a different filename for the second method to prevent that.
Found a second trap. You don't specify full file path in first method, but in second. If C:\Users\Databoe\Documents\KidsTV is not your default document path, you have 2 grade.csv in different folders, but you maybe think that you only have one that gets overwritten.
I just ran into this problem myself, and found a great work around. It doesn't save as a .csv, but you can save as a comma delimited .txt file.
Use the export wizard on the External Data tab to export your query as a .txt file without formatting.
Once the file is exported you get a dialogue box asking if you want to save export steps. Click the box and save the export.
There is an action available in the Macro wizard called "Run Saved Import/Export." Select this action and choose your saved export from the dropdown menu.
Very frustrating that even now I cant seem to make Access export a simple csv file. I do not know why they think I need pretty formatting. Try this: open Excel, Click Get Data, From Database, From MicroSoft Access Database. Select the Access Database you wish to export from. Select the table/query we want saved as an csv. This will set up a link to this table. Once imported, save the Excel file to an csv file.

External file properties not updated - VBA

I have a macro that reads out external file properties like date created. The file from where I read is stored on a server. Unfortunately the date returned is not the correct one when running the macro the first time. Only when I open the file or when I run the macro several times, the correct updated date created is returned.
Does anyone have an idea how to solve that issue except from opening the file or looping through until the date is correct?
Here is the code:
strFilename = "<FILENAME>"
Workbooks.Open strFilename
Workbooks("strFilename").Close
Set oFS = CreateObject("Scripting.FileSystemObject")
lastcreatedLTVfile = CDate(Format(oFS.GetFile(strFilename).DateCreated, "dd.mm.yyyy"))
Do you want DateCreated or do you actually want DateLastModified? In your question you say "correct updated date" so I guess you should be using DateLastModified.

How to search data in a txt file through Visual Basic

I have this txt file with the following information:
National_Insurence_Number;Name;Surname;Hours_Worked;Price_Per_Hour so:
eg.: aa-12-34-56-a;Peter;Smith;36;12
This data has been inputed to the txt file through a VB form which works totally fine, the problem comes when, on another form. This is what I expect it to do:
The user will input into a text box the employees NI Number.
The program will then search through the file that NI Number and, if found;
It will fill in the appropriate text boxes with its data.
(Then the program calculates tax and national insurance which i got working fine)
So basically the problem comes telling the program to search that NI number and introduce each ";" delimited field into its corresponding text box.
Thanks for all.
You just need to parse the file like a csv, you can use Microsoft.VisualBasic.FileIO.TextFieldParser to do this or you can use CSVHelper - https://github.com/JoshClose/CsvHelper
I've used csv helper in the past and it works great, it allows you to create a class with the structure of the records in your data file then imports the data into a list of these for searching.
You can look here for more info on TextFieldParser if you want to go that way -
Parse Delimited CSV in .NET
Dim afile As FileIO.TextFieldParser = New FileIO.TextFieldParser(FileName)
Dim CurrentRecord As String() ' this array will hold each line of data
afile.TextFieldType = FileIO.FieldType.Delimited
afile.Delimiters = New String() {";"}
afile.HasFieldsEnclosedInQuotes = True
' parse the actual file
Do While Not afile.EndOfData
Try
CurrentRecord = afile.ReadFields
Catch ex As FileIO.MalformedLineException
Stop
End Try
Loop
I'd recommend using CsvHelper though, the documentation is pretty good and working with objects is much easier opposed to the raw string data.
Once you have found the record you can then manually set the text of each text box on your form or use a bindingsource.

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 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
loop files
if merged_spreadsheet is not nothing
save it
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