|
- Option Explicit
- Sub Test()
- Dim shResult As Worksheet
- Dim strFilePath As String, strFileName As String
- Dim strText As String, strSplit() As String
- Dim rgFileName As Range, rgResult As Range, lngRows As Long
- Dim arrFileName As Variant, arrResult As Variant
-
- Set shResult = Sheets("结果")
- Set rgFileName = shResult.Range("A2")
- Set rgResult = shResult.Range("B2")
- shResult.UsedRange.ClearContents
- shResult.Range("A1:C1") = Array("txt文件名", "数据1", "数据2")
-
- strFilePath = ThisWorkbook.Path & ""
- strFileName = "*.txt"
- strFileName = Dir(strFilePath & strFileName)
- Do While strFileName <> ""
- strText = GetContentByTxt(strFilePath & strFileName)
- strSplit = Split(strText, ";")
- lngRows = UBound(strSplit) + 1
- rgFileName.Resize(lngRows, 1) = Replace(strFileName, ".txt", "")
- rgResult.Resize(lngRows, 1) = Application.WorksheetFunction.Transpose(strSplit)
- rgResult.Resize(lngRows, 1).TextToColumns Destination:=rgResult, DataType:=xlDelimited, Comma:=True
- Set rgFileName = rgFileName.Offset(lngRows, 0)
- Set rgResult = rgResult.Offset(lngRows, 0)
- strFileName = Dir()
- Loop
- MsgBox "OK"
- End Sub
- Function GetContentByTxt(strFilePathAndName As String) As String
- Dim objFS As Object, objTS As Object
- Set objFS = CreateObject("Scripting.FileSystemObject")
- Set objTS = objFS.OpenTextFile(strFilePathAndName)
- GetContentByTxt = objTS.ReadAll
- objTS.Close: Set objTS = Nothing
- Set objFS = Nothing
- End Function
复制代码 |
|