VBA open files, edit, save - vba

I am trying to find a code which solves the following problem:
open a couple of csv files in one folder
run a formatting
save it as a xlsx file
The code for the formatting I have already in place. I just do not know how to open all files automatically, do the formatting and save them.
Looking forward to your answers.
Best

To open a file, you can modify this code(location & file name with extension):
patH = "C:\General\"
filE = "Example.csv"
Workbooks.Open Filename:=patH & filE
To save the formatted file, you can modify this code below(will overwrite if a file with same name exists):
path2 = "C:\General\"
file2 = "Example2"
dirFile = path2 & file2
ThisWorkBook.SaveAs dirFile, AccessMode:=xlExclusive, _
ConflictResolution:=Excel.XlSaveConflictResolution.xlLocalSessionChanges

Related

How can I batch convert .doc files into .txt so I can import into Excel

I need to transfer data from a number of Word (mostly .doc, some .docx) files into Excel for better documentation & analysis.
Currently the only way I see to do this is: manually open each file > Save As > plain text > Windows (default). This is arduous and not a good use of time as I have hundreds of documents to do this for.
I am an absolute novice with VBA and Macros, but imagine I can automate most of the work with these.
Alternatively, would PowerShell be able to do this?
I tried following this suggestion to batch convert Word to .txt but when I opened the .txt files they were all blank. If i follow the manual one-by-one SaveAs route, then they have the data saved as text.
If the code you were using didn't work for you it suggests that the documents you have don't contain form fields. To simply save the documents as text all you need to do is omit the SaveFormsData:=True, as below.
Sub SaveAllFormData(path As String)
Dim doc As Document
Dim fileName As String
fileName = Dir(path & "*.doc*")
' Loop through all .doc files in that path
Do While fileName <> ""
Set doc = Application.Documents.Open(path & fileName)
' Save form data
doc.SaveAs2 doc.FullName & ".txt", WdSaveFormat.wdFormatText
doc.Close wdDoNotSaveChanges
fileName = Dir
Loop
End Sub

Visual Basic: Save in same folder as Excel Sheet

I'm very new to VB, so this is probably a very easy one. I'm creating a Word document from an Excel spreadsheet, and would like the Word doc to save in the same folder location as the spreadsheet.
I'm using the code:
.SaveAs Filename:=ThisWorkbook.Path & Range("C8").Text & ".docx"
Which I though would work, but it saves it in teh directory up from the location.
I.e. the spreadsheet is in C:/User/Documents/MySpreadsheet. But the Word doc would be saved in C:/User/Documents.
I also made a message popup to display ThisWorkbook.Path which comes up with the Spreadsheet path, so I know that's right!
I also don't think I've done the naming right, as I would like it to be named the text in cell C8. But it's actually the 'Documents' folder name with the text in C8 added on.
Thanks in advance.
Activate Immediate Window (Ctrl+G) and and add this line to your code:
debug.print ThisWorkbook.Path & Range("C8").Text & ".docx"
You will see if your path is correct. In particular, if you have "\" between folder path and filename.

Remove blank lines from the end of a text file

I have written a sub routine which converts the data within an excel work sheet to a text file and saves it but it leaves me with a lot of blank lines at the end of the text file. As a different amount of data can be taken by this tab every time it is run, I assume that is what's causing the issue but I can't see that there is much I can do to change that as the data needs to be processed. Is there a way, using VBA, to remove the empty lines (white space) at the end of the text file or a better approach so it doesn't create the empty rows in the first place? I have done some searching and I can't find much on the subject using VBA. PLease help ?!
'Selects appropriate worksheet - Non-MyPayFINAL
Sheets("Non-MyPay FINAL").Select
'Selects all data in column A and copies to clipboard
Range("A1", Range("A1").End(xlDown)).Select
Selection.Copy
'Add a new workbook
Workbooks.Add
'Paste selected values from previous sheet
Selection.PasteSpecial Paste:=xlPasteValues
'Build SaveAs file name (for CSV file)
MySaveFile = Format(Now(), "DDMMYYYY") & "NonMyPayFINAL" & ".CSV"
'Save template file as...(for CSV file)
ActiveWorkbook.SaveAs ("S:\MERIT OUTPUTS FOLDER\MSI Recruitment
Limited\" & MySaveFile), FileFormat:=xlCSV
'Build SaveAs file name (for Txt file)
MySaveFile = Format(Now(), "DDMMYYYY") & "NonMyPayFINAL" & ".Txt"
'Save template file as...(for Txt file)
ActiveWorkbook.SaveAs ("S:\MERIT OUTPUTS FOLDER\MSI Recruitment
Limited\" & MySaveFile), FileFormat:=xlTextWindows
I have updated with the section of code which copies and creates the text file which I think is where the issue is. Any help with this would be greatly appreciated.
I have found the below code which goes a long way by allowing me to add text to the end of a txt file, can the same be used to remove text as well, apologies if this seems simple but I haven't quite got the hang of this yet.
Sub TextFile_Create()
'PURPOSE: Add More Text To The End Of A Text File
Dim TextFile As Integer
Dim FilePath As String
'What is the file path and name for the new text file?
FilePath = "S:\MERIT OUTPUTS FOLDER\MSI Recruitment
Limited\11072017MyPayFINAL.txt"
'Determine the next file number available for use by the FileOpen
function
TextFile = FreeFile
'Open the text file
Open FilePath For Append As TextFile
'Write some lines of text
Print #TextFile, "Sincerely,"
Print #TextFile, ""
Print #TextFile, "Chris"
'Save & Close Text File
Close TextFile
End Sub
1. Robust and basic way to delete "blanks" from the end of a text line:
For each line of your text file: read into string, get last character, delete if it is a "blank"; repeat until it is not a blank any more, write line to new file
2. Remove blanks with existing functions
If you have no other blanks, you can just use the 'replace' function, documentation here. Just replace the blank (e.g. " ") with "". For only deleting leading and/or trailing blanks use the trim function.
3. Parse before writing to file (recommended):
Check the output with one of the above mentioned methods before writing it to the file.
Just be careful about the characters you actually want to remove. If in doubt, view your created text file in an editor that can show you all characters.
Update
If you want to write specific data instead of the whole sheet, you need to adjust your script accordingly. This SO answer will give you a good start on how to write specific data to a file. Combined with the mentioned functions you should be good to go.
2nd Update
To remove leading and/or trailing spaces from a string, you can use the trim function as mentioned above. Here are examples and the documentation.

Save Excel table in current folder

I want to save my current table as a text file in the same folder as the current workbook (that is open).
I use this code:
ActiveWorkbook.SaveAs ThisWorkbook.path & "\" & filename
For some reason it save the text file in the same folder as my personal.xlsb.
I use Office 2010
If this is not possible to do easily then maybe one can force Excel to open a browse window where I can pick where I want the file saved.
ThisWorkbook points to the location where the code is written. In your case personal.xlsb.
If you want to save the table in the same directory as the active workbook, use ActiveWorkbook.path instead.
You may try this
ChDir "C:\yourfolder"
ActiveWorkbook.SaveAs Filename:= _
"c:\yourfolder" & filename & ".txt", FileFormat:=xlText, _
In this example I have created a folder name "yourfolder" in my C drive. The created text file will save in C\yourfolder\filenane.txt
Hope this is helpful

Saving an Excel sheet in a current directory with VBA

I have created a sheet in vba Excel. I would like to save it the current directory, but not in absolute path, then, when this is executed somewhere else, there won't be problem.
Can somebody help ?
I am not clear exactly what your situation requires but the following may get you started. The key here is using ThisWorkbook.Path to get a relative file path:
Sub SaveToRelativePath()
Dim relativePath As String
relativePath = ThisWorkbook.Path & Application.PathSeparator & ActiveWorkbook.Name
ActiveWorkbook.SaveAs Filename:=relativePath
End Sub
VBA has a CurDir keyword that will return the "current directory" as stored in Excel. I'm not sure all the things that affect the current directory, but definitely opening or saving a workbook will change it.
MyWorkbook.SaveAs CurDir & Application.PathSeparator & "MySavedWorkbook.xls"
This assumes that the sheet you want to save has never been saved and you want to define the file name in code.
If the Path is omitted the file will be saved automaticaly in the current directory.
Try something like this:
ActiveWorkbook.SaveAs "Filename.xslx"
Taking this one step further, to save a file to a relative directory, you can use the replace function. Say you have your workbook saved in: c:\property\california\sacramento\workbook.xlsx, use this to move the property to berkley:
workBookPath = Replace(ActiveWorkBook.path, "sacramento", "berkley")
myWorkbook.SaveAs(workBookPath & "\" & "newFileName.xlsx"
Only works if your file structure contains one instance of the text used to replace. YMMV.