Remove blank lines from the end of a text file - vba

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.

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.

Excel VBA code is causing my worksheets to appear as jargon

I currently am using a VBA macro that I found here on stack over flow. The problem is when I run it it saves all the data into a separate excel sheet but when i open it it appears as "jargon" in other words unreadable type. This is the "Save code"
'Save the new workbook, and close it
wb.SaveAs ThisWorkbook.Path & "\test" & WorkbookCounter
wb.Close
The way I am currently running the code is that it separates my excel sheets into different spread sheets by rows of 250. Everything works but when I open the saved documents it says that this file format is unacceptable to Excel. Then I try importing it and I get an error. Here is a snap shot of the way it appears in my screen. Also here is the file name: built.list\test.xls39
Your workbook counter always ends in a number, Windows and Excel use the file extension to determine file-type, so an '.xls39' file is unrecognisable. Try:
wb.SaveAs _
Filename:=ThisWorkbook.Path & "\test" & WorkbookCounter & ".xls" _
FileFormat:=XlFileFormat.xlExcel8
'Use xlOpenXMLWorkbook for the .xlsx format
(Use space followed by underscore to separate lines in VBA)
Or make sure WorkbookCounter ends in .xls and not a number.
(Edit: For other formats, please look in the References dialog in Excel VBA Editor)

Loop through specific folder of csv, merging the 1st row of each into one workbook

I've looked through several posts and can't seem to find a suitable answer - similar, but not quite what I'm looking for.
I would like some code that loops through a series of csv-files (~ 200 at a time) within a specific folder. It needs to import/copy the values of the first row of each of these csv-files to one (main) workbook. These csv-file-names are numerical (eg 20140213075458) any files that does not meet this criteria (14 characters, numbers only AND FileFormat = csv) should not be considered.
Any guidance will be much appreciated!
Add the Microsoft Scripting Runtime library to your project and use Use FileSystemObject class to loop through all files. You can use the Like operator to check if file name matches your criteria.
i think this add-in might help you for sure.
RDBMerge used to Merge Data from Multiple Excel Workbooks,
csv and xml files into a Summary Workbook.
I am just going to outline the operations you need to do. You can work from that.
Get the filename of each file in each folder: fname = Dir(Your_Folder_Path)
Initialize file read counter: i=1
Loop through all files in folder:
Do While fname <> "" 'Loop all files in folder
Check your conditions:
Extension = Split(fname, ".")(Ubound(Split(fname, "."))) 'Extract extension of file
Name = Split(fname, ".")(Ubound(Split(fname, "."))-1) 'Extract name of file without extension
If Extension = "csv" And Len(Name) = 14 And IsNumeric(Name) Then 'Check csv, length of name 14 and numeric name
Open csv, read first line and close it:
Open Your_Folder_Path & fname For Input As #f1
Line Input #f1, csvFirstLine
Close #f1
Put data in workbook:
ActiveSheet.Range("A" & i).Value = csvFirstLine 'Put line in corresponding row
ActiveSheet.Range("A" & i).TextToColumns Comma:=True 'Separate data by comma
i=i+1 'File counter +1
Exit ifs and close loops: End If Loop

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.