|
[广告] VBA代码宝 - VBA编程加强工具 · VBA代码随查随用 · 内置多项VBA编程加强工具 ★ 免费下载 ★ ★ 使用手册★
下面代码,执行时候把存放代码的文件和需要读取的txt文件放在同一个文件夹即可- Sub 遍历文件夹()
- Dim arr0(), arr1()
- Dim arr
- Dim bkName, pth, bkNames, i, k, k1, j
- bkName = ThisWorkbook.Name
- pth = ThisWorkbook.Path
- bkNames = Dir(pth & "" & "*.*")
- Do Until bkNames = ""
- If bkNames <> bkName And bkNames Like "*.txt*" Then
- i = i + 1
- ReDim Preserve arr0(1 To i)
- arr0(i) = bkNames
- End If
- bkNames = Dir
- Loop
- For k = 1 To UBound(arr0)
- Dim objstream, strData
- Dim Str$
- Set objstream = CreateObject("ADODB.Stream")
- objstream.Charset = "utf-8"
- objstream.Open
- objstream.LoadFromFile (ThisWorkbook.Path & "" & arr0(k))
- strData = objstream.ReadText()
- arr = Split(strData, vbCrLf)
- Str = ""
- For j = 0 To UBound(arr) - 1
- Str = Str & arr(j)
- Next
- objstream.Close
- Set objstream = Nothing
- k1 = k1 + 1
- ReDim Preserve arr1(1 To k1)
- arr1(k1) = Str
- Next
- Range("r2:r" & UBound(arr1) + 1) = Application.Transpose(arr1)
- End Sub
复制代码 |
|