找回密码
 注册

QQ登录

只需一步,快速开始

查看: 283|回复: 1

Batch converting text file into Excel files

[复制链接]
发表于 2013-11-22 15:58:40 | 显示全部楼层 |阅读模式
It's a pretty simple function but with little complecated description.

Like there are around 10 branches with balance data from 2002 to 2013. history data only need annual and 2013 need ytd monthly based files.

File name as Belance_sheet_Branch_month_day_Year.text, and to be converted to the same name but put into respected folders.

Here is what has done.
  1. '**************************
  2. '*Code By: John Z
  3. '*Function: Batch converting text files into Excel files with sepecific format regulated
  4. '*Email: cq_box#163.com
  5. '*Date: November 11, 2013
  6. '**************************

  7. Sub BatchConvertFiles()
  8.      
  9.     Dim objFSO As Object
  10.     Dim objFolder As Object
  11.     Dim objFile As Object
  12.     Dim ws As Worksheet
  13.     Dim SourceRoot, DestRoot As String, mArr As Variant
  14.     Dim ExtFile, Basepath, Branch, DateStr, BaseFile, NewFile, sYear, m_text As String
  15.      
  16.     SourceRoot = "X:\Source\balance_convert\all"
  17.     DestRoot = "X:\ARCHIVE\balance_sheet"
  18.     Set objFSO = CreateObject("Scripting.FileSystemObject")
  19.     Set ws = ActiveSheet
  20.     'Set ws = Worksheets.Add --Debug use

  21.      'Get the folder object associated with the directory
  22.     Set objFolder = objFSO.GetFolder(SourceRoot)
  23.     'ws.Cells(1, 1).Value = "The files found in " & objFolder.Name & " are:"
  24.      
  25.      'Loop through the Files collection
  26.     For Each objFile In objFolder.Files
  27.         'ws.Cells(ws.UsedRange.Rows.Count + 1, 1).Value = objFile.Name
  28.         m_text = objFile.Name
  29.         mArr = Split(m_text, ".")
  30.         ExtFile = mArr(1)
  31.         BaseFile = mArr(0)
  32.         NewFile = mArr(0) & ".xlsx"
  33.         mArr = Split(mArr(0), "_")
  34.         Basepath = mArr(0) & "_" & mArr(1)
  35.         Branch = mArr(2): DateStr = mArr(3)
  36.         sYear = "20" & Split(mArr(3), "-")(2)
  37.         NewFile = DestRoot & "" & Branch & "" & sYear & "" & NewFile
  38.         
  39.         '"TEXT;X:\ARCHIVE\balance_sheet\kam\2002\balance_sheet_B01_12-31-02.txt",  --- File Name example
  40.     With ActiveSheet.QueryTables.Add(Connection:= _
  41.         "TEXT;" & SourceRoot & "" & objFile.Name, _
  42.         Destination:=Range("$A$1"))
  43.         .Name = BaseFile 'Name the sheet tag with file name "balance_sheet_B01_12-31-02"
  44.         .FieldNames = True
  45.         .RowNumbers = False
  46.         .FillAdjacentFormulas = False
  47.         .PreserveFormatting = True
  48.         .RefreshOnFileOpen = False
  49.         .RefreshStyle = xlInsertDeleteCells
  50.         .SavePassword = False
  51.         .SaveData = True
  52.         .AdjustColumnWidth = True
  53.         .RefreshPeriod = 0
  54.         .TextFilePromptOnRefresh = False
  55.         .TextFilePlatform = 850
  56.         .TextFileStartRow = 1
  57.         .TextFileParseType = xlFixedWidth
  58.         .TextFileTextQualifier = xlTextQualifierDoubleQuote
  59.         .TextFileConsecutiveDelimiter = False
  60.         .TextFileTabDelimiter = True
  61.         .TextFileSemicolonDelimiter = False
  62.         .TextFileCommaDelimiter = False
  63.         .TextFileSpaceDelimiter = False
  64.         .TextFileColumnDataTypes = Array(2, 2, 1, 1)
  65.         .TextFileFixedColumnWidths = Array(12, 42, 16)    'Data fields delimilite
  66.         .TextFileTrailingMinusNumbers = True
  67.         .Refresh BackgroundQuery:=False
  68.     End With
  69.     ChDir DestRoot & "" & Branch & "" & sYear
  70.     '"X:\ARCHIVE\balance_sheet\B01\2002" --sample of destination folder location
  71.     ActiveWorkbook.SaveAs Filename:= _
  72.         NewFile, _
  73.         FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
  74.         
  75.         '"X:\ARCHIVE\balance_sheet\B01\2002\balance_sheet_B01_12-31-02.xlsx", _ --another data example format

  76.         'ws.Cells(ws.UsedRange.Rows.Count, 2).Value = NewFile
  77.         'MsgBox ("Destnation: " & DestRoot & "" & Branch & "" & sYear & "" & NewFile)
  78.         Call clearall
  79.     Next
  80.      
  81.      'Clean up!
  82.     Set objFolder = Nothing
  83.     Set objFile = Nothing
  84.     Set objFSO = Nothing
  85. End Sub

  86. '**************************
  87. '*Code By: John Z
  88. '*Function: Another sample module to list out all the files required. this one cannot go succeed in new version of excel after 2007
  89. '*Email: cq_box#163.com
  90. '*Date: November 11, 2013
  91. '**************************
  92. Sub ListAllFiles()
  93.     Dim fs As FileSearch, ws As Worksheet, i As Long
  94.     Set fs = Application.FileSearch
  95.     With fs
  96.         .SearchSubFolders = False ' set to true if you want sub-folders included
  97.         .FileType = msoFileTypeAllFiles 'can modify to just Excel files eg with msoFileTypeExcelWorkbooks
  98.         .LookIn = "X:\jzx\balance_convert\all" 'modify this to where you want to serach
  99.         If .Execute > 0 Then
  100.             Set ws = Worksheets.Add
  101.             For i = 1 To .FoundFiles.Count
  102.                 ws.Cells(i, 1) = .FoundFiles(i)
  103.             Next
  104.         Else
  105.             MsgBox "No files found"
  106.         End If
  107.     End With
  108. End Sub

  109. '**************************
  110. '*Code By: John Z
  111. '*Function: list out files with short file name
  112. '*Email: cq_box#163.com
  113. '*Date: November 11, 2013
  114. '**************************
  115. Sub ListAllFilesShort()
  116.     Dim fs As FileSearch, ws As Worksheet, i As Long
  117.     Set fs = Application.FileSearch
  118.     With fs
  119.         .SearchSubFolders = False ' set to true if you want sub-folders included
  120.         .FileType = msoFileTypeAllFiles 'can modify to just Excel files eg with msoFileTypeExcelWorkbooks
  121.         .LookIn = "C:" 'modify this to where you want to serach
  122.         If .Execute > 0 Then
  123.             Set ws = Worksheets.Add
  124.             For i = 1 To .FoundFiles.Count
  125.                 ws.Cells(i, 1) = Mid$(.FoundFiles(i), InStrRev(.FoundFiles(i), "") + 1)
  126.             Next
  127.         Else
  128.             MsgBox "No files found"
  129.         End If
  130.     End With
  131. End Sub

  132. Sub clearall()
  133. '**************************
  134. '*Module name: clearall
  135. *Code By: John Z
  136. '*Function: clear specific area for sheet reuse.
  137. '*Email: cq_box#163.com
  138. '*Date: November 11, 2013
  139. '**************************'
  140. '
  141.     Range("A:D").Select
  142.     Selection.ClearContents
  143.     Range("A1").Select
  144. End Sub
复制代码



来自圈子: Demo俱乐部
 楼主| 发表于 2013-11-27 14:06:53 | 显示全部楼层

Batch converting text file in tree dictories into Excel files

An update version used as above.
Even the source data is all sitted in different folders.
  1. Sub clearall()
  2. '
  3. ' clearall Macro
  4. '

  5. '
  6.     Range("A:K").Select
  7.     Selection.ClearContents
  8.     Range("A1").Select
  9. End Sub

  10. Sub ConvertAll_Income()
  11. '
  12. 'John Z
  13. 'Description:
  14. 'example for executing the function ListFilesInFolder
  15.      
  16.     Dim SourceRoot As String
  17.     Workbooks.Add
  18.     SourceRoot = "X:\ARCHIVE\income_statement"
  19.     ListFilesInFolder SourceRoot, True
  20.     MsgBox ("Done!")
  21. End Sub

  22. Sub ListFilesInFolder(ByVal SourceFolderName As String, ByVal IncludeSubfolders As Boolean)
  23. '
  24. ' John Z
  25. ' http://www.bcmorning.com/forum.php?mod=forumdisplay&fid=109
  26. ' description:
  27. ' lists information about the files in SourceFolder, and convert all text files into excel files.
  28. ' example: ListFilesInFolder "C:\FolderName", True
  29. '
  30.     Dim FSO As Object
  31.     Dim SourceFolder As Object
  32.     Dim SubFolder As Object
  33.     Dim FileItem As Object
  34.     Dim ExtFile, m_text As String ', BasePath, Branch, DateStr, BaseFile, NewFile, sYear
  35.    
  36.     Set FSO = CreateObject("Scripting.FileSystemObject")
  37.     Set SourceFolder = FSO.GetFolder(SourceFolderName)
  38.     'r = Range("A65536").End(xlUp).Row + 1
  39.     For Each FileItem In SourceFolder.Files
  40.         'display file properties
  41.         m_text = FileItem.Name
  42.         mArr = Split(m_text, ".")
  43.         ExtFile = mArr(1)
  44.         If ExtFile = "txt" And FileItem.Size > 0 Then
  45.             ConvertToExcel FileItem.Path ', NewFile
  46.         End If
  47.         'X = SourceFolder.Path
  48.     Next FileItem
  49.     If IncludeSubfolders Then
  50.         For Each SubFolder In SourceFolder.SubFolders
  51.             ListFilesInFolder SubFolder.Path, True
  52.         Next SubFolder
  53.     End If

  54.     '***** Remove the single ' character in the below lines to adjust the column windths
  55.     'Columns("A:G").ColumnWidth = 4
  56.     'Columns("H:I").AutoFit
  57.     'Columns("J:L").ColumnWidth = 12
  58.     'Columns("M:P").ColumnWidth = 8

  59.     Set FileItem = Nothing
  60.     Set SourceFolder = Nothing: Set SubFolder = Nothing
  61.     Set FSO = Nothing
  62.     'ActiveWorkbook.Saved = True
  63. End Sub

  64. Function ConvertToExcel(ByVal SourceFile As String) ', ByVal DestFileName As String)
  65.     Dim myFSO, myFile As Object
  66.     Dim mArr As Variant
  67.     Dim m_text, m_path, ExtFile, BaseFile, NewFile, DateStr, Branch, BasePath, sYear As String
  68.    
  69.     Set myFSO = CreateObject("Scripting.FileSystemObject")
  70.     Set myFile = myFSO.GetFile(SourceFile)
  71.    
  72.     m_text = myFile.Name
  73.     m_path = myFile.Path
  74.     mArr = Split(m_text, ".")
  75.     BaseFile = mArr(0)
  76.     ExtFile = mArr(1)
  77.     mArr = Split(m_path, ".")
  78.     NewFile = mArr(0) & ".xlsx"
  79.     'mArr = Split(mArr(0), "_")
  80.     'BasePath = mArr(0) & "_" & mArr(1)
  81.     'Branch = mArr(2): DateStr = mArr(3)
  82.     'sYear = "20" & Split(mArr(3), "-")(2)
  83.     'NewFile = DestFileName 'DestFolder & "" & Branch & "" & sYear & "" & NewFile

  84.     With ActiveSheet.QueryTables.Add(Connection:= _
  85.         "TEXT;" & SourceFile, _
  86.         Destination:=Range("$A$1"))
  87.         '"TEXT;" & SourceRoot & "" & objFile.Name,
  88.         .Name = BaseFile
  89.         .FieldNames = True
  90.         .RowNumbers = False
  91.         .FillAdjacentFormulas = False
  92.         .PreserveFormatting = True
  93.         .RefreshOnFileOpen = False
  94.         .RefreshStyle = xlInsertDeleteCells
  95.         .SavePassword = False
  96.         .SaveData = True
  97.         .AdjustColumnWidth = True
  98.         .RefreshPeriod = 0
  99.         .TextFilePromptOnRefresh = False
  100.         .TextFilePlatform = 850
  101.         .TextFileStartRow = 1
  102.         .TextFileParseType = xlFixedWidth
  103.         .TextFileTextQualifier = xlTextQualifierDoubleQuote
  104.         .TextFileConsecutiveDelimiter = False
  105.         .TextFileTabDelimiter = True
  106.         .TextFileSemicolonDelimiter = False
  107.         .TextFileCommaDelimiter = False
  108.         .TextFileSpaceDelimiter = False
  109.         .TextFileColumnDataTypes = Array(2, 2, 1, 1, 1, 1, 1, 1, 1, 1)
  110.         .TextFileFixedColumnWidths = Array(14, 44, 12, 8, 14, 8, 14, 8, 14, 8)
  111.         .TextFileTrailingMinusNumbers = True
  112.         .Refresh BackgroundQuery:=False
  113.     End With
  114.     'ChDir DestRoot & "" & Branch & "" & sYear
  115.     '"X:\ARCHIVE\balance_sheet\b01\2002"
  116.     ActiveWorkbook.SaveAs FileName:= _
  117.         NewFile, _
  118.         FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
  119.         
  120.         '"X:\ARCHIVE\balance_sheet\b01\2002\balance_sheet_b01_12-31-02.xlsx", _

  121.         'ws.Cells(ws.UsedRange.Rows.Count, 2).Value = NewFile
  122.         'MsgBox ("Destnation: " & DestRoot & "" & Branch & "" & sYear & "" & NewFile)
  123.     Call clearall
  124. End Function

  125. Function GetFileOwner(ByVal FilePath As String, ByVal FileName As String)
  126.     Dim objFolder As Object
  127.     Dim objFolderItem As Object
  128.     Dim objShell As Object
  129.     FileName = StrConv(FileName, vbUnicode)
  130.     FilePath = StrConv(FilePath, vbUnicode)
  131.     Set objShell = CreateObject("Shell.Application")
  132.     Set objFolder = objShell.Namespace(StrConv(FilePath, vbFromUnicode))
  133.     If Not objFolder Is Nothing Then
  134.         Set objFolderItem = objFolder.ParseName(StrConv(FileName, vbFromUnicode))
  135.     End If
  136.     If Not objFolderItem Is Nothing Then
  137.         GetFileOwner = objFolder.GetDetailsOf(objFolderItem, 8)
  138.     Else
  139.         GetFileOwner = ""
  140.     End If
  141.     Set objShell = Nothing
  142.     Set objFolder = Nothing
  143.     Set objFolderItem = Nothing
  144. End Function
复制代码
Any suggests are welcomed.

您需要登录后才可以回帖 登录 | 注册

本版积分规则

手机版|小黑屋|BC Morning Website ( Best Deal Inc. 001 )

GMT-8, 2026-6-10 18:52 , Processed in 0.014232 second(s), 15 queries .

Supported by Weloment Group X3.5

© 2008-2026 Best Deal Online

快速回复 返回顶部 返回列表