Hello all,
This is my first time with VBA Macros in excel. My query may be a basic one but appreciate any help on this.
I have a folder where I have multiple excel( .xlsx) files with 2 or more worksheets.
e.g
00.XLSX
01.XLSX
02.XLSX
Each of these has 2 worksheets a)Header b) Detail
My requirement is that the macro should loop over each of the excel files in the folder and select each of the worksheets convert it into a text file. So basically my output would look like ( files converted)
00_Header.txt
00_Detail.txt
01_Header.txt
01_detail.txt
02_Header.txt
02_Detail.txt
I found various snippets here and I framed a bit of code of my own. But Now I am stuck up here especially in the loop for handling the worksheets of the workbook.
Any help would be really appreciated and I would be thankful for it.
Code:
===
Sub loopandconverttoTEXT()
Dim WS As Worksheets
Dim newname As String
Dim strpath as String
strpath = "C:\Desktop\Test"
Set objExcel = CreateObject("Excel.Application")
objExcel.Visible = True
objExcel.DisplayAlerts = False
Set objFso = CreateObject("Scripting.FileSystemObject")
Set objFolder = objFso.GetFolder(strpath)
For Each objFile In objFolder.Files
If objFso.GetExtensionName(objFile.Path) = "xlsx" Then
Set objWorkbook = objExcel.Workbooks.Open(objFile.Path)
For Each WS In objWorkbook.Worksheets
newname = GetBookName(objWorkbook.Name) & "_" & WS.Name
WS.Copy
objWorkbook.SaveAs strpath & newname & ".txt"
objWorkbook.Close True 'Save changes
Next
End If
Next
objExcel.Quit
End Sub
Function GetBookName(strwb As String) As String
GetBookName = Left(strwb, (InStrRev(strwb, ".", -1, vbTextCompare) - 1))
End Function
=====
Thanks.
Moderator's Edit: Use code tags when posting code. To do so in future, select the code and click on the # icon at the top of your post window.
Bookmarks