Results 1 to 6 of 6

Loop all excel files in a directory and convert each worksheet of the excel files to text

Threaded View

  1. #1
    Registered User
    Join Date
    01-07-2013
    Location
    Canada
    MS-Off Ver
    Excel 2003
    Posts
    6

    Loop all excel files in a directory and convert each worksheet of the excel files to text

    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.
    Last edited by arlu1201; 01-08-2013 at 02:03 AM.

Thread Information

Users Browsing this Thread

There are currently 1 users browsing this thread. (0 members and 1 guests)

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts

Search Engine Friendly URLs by vBSEO 3.6.0 RC 1