我想知道,如何獲取“C/Windows”中所有子檔案夾的串列并將其寫入 txt 檔案。這是我的代碼:
Sub Check
MkDir "c:\New_Folder"
Dim iFileNo as Integer
Dim strFile As String
strFile = "c:\New_Folder\data.txt" 'the file you want to save to
intFile = FreeFile
Open strFile For Output As #intFile
Print #intFile,
Close #intFile
End Sub
完整解釋:寫一個程式,比如打開D盤的檔案夾(檔案夾就是你的昵稱)。在此檔案夾中打開檔案 data.txt,在其中記下目錄 C:\Windows 中所有檔案夾的名稱。2. 撰寫一個程式,從檔案中讀取資訊,該檔案是用第一個程式打開的,并通過 MsgBox 皮膚將另一行傳輸到檔案中
uj5u.com熱心網友回復:
每當問題被定義為“獲取所有子檔案夾的串列”和“寫入文本檔案”時,我知道我可能需要實作某種回圈。事實證明,這就是您的代碼中缺少的全部內容。該Dir命令可以幫助解決這個問題:
Private Sub Check()
Dim intFile As Integer
Dim strFile As String
Dim FolderName As String
MkDir "c:\New_Folder"
strFile = "c:\New_Folder\data.txt"
intFile = FreeFile
Open strFile For Output As #intFile
FolderName = Dir("c:\windows\", vbDirectory)
Do While FolderName <> ""
If FolderName <> "." And FolderName <> ".." And (GetAttr("c:\windows\" & FolderName) And vbDirectory) = vbDirectory Then
Print #intFile, FolderName
End If
FolderName = Dir()
Loop
Close #intFile
End Sub
我還鼓勵您使用正確的代碼格式,在這種情況下是縮進。它會讓你的生活在某個時候更輕松!
uj5u.com熱心網友回復:
沒有錯誤檢查的基本示例:
Sub Tester()
Dim f
For Each f In AllFolders("D:\Analysis")
Debug.Print f
Next f
End Sub
'return all folders which are subfolders of `startFolder`
Function AllFolders(startFolder As String)
Dim col As New Collection, colOut As New Collection, f, sf
col.Add startFolder
Do While col.Count > 0
f = col(1) & IIf(Right(f, 1) <> "\", "\", "")
col.Remove 1
sf = Dir(f, vbDirectory) 'fetch folders also
Do While Len(sf) > 0
If GetAttr(f & sf) = vbDirectory Then 'is this a folder ?
If sf <> "." And sf <> ".." Then 'ignore self or parent
col.Add f & sf & "\" 'add to list to check for subfolders
colOut.Add f & sf 'add to output
End If
End If
sf = Dir
Loop
Loop
Set AllFolders = colOut
End Function
uj5u.com熱心網友回復:
請嘗試下一個代碼:
Sub testGetSubFolders()
Dim strFold As String, strFile As String, arrTxt
strFold = "C:\Windows"
If dir("c:\New_Folder", vbDirectory) = "" Then 'if the folder does not exist
MkDir "c:\New_Folder" 'it is created
End If
strFile = "c:\New_Folder\data.txt"
arrTxt = GetSubFolders(strFold) 'receive an array of subfolders
Open strFile For Output As #1
Print #1, Join(arrTxt, vbCrLf) 'join the array on end of line
Close #1
End Sub
Function GetSubFolders(strFold As String) As Variant 'it returns an array of subfolders path
Dim fso, fldr, subFldr, arr, i As Long
Set fso = CreateObject("Scripting.FileSystemObject")
Set fldr = fso.GetFolder(strFold)
ReDim arr(fldr.subFolders.count - 1) 'redim the array to keep the paths
For Each subFldr In fldr.subFolders
arr(i) = subFldr.Path: i = i 1 'place the paths in the array and increment i
Next subFldr
GetSubFolders = arr
End Function
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/373211.html
