操纵文件:
1. 创建新文件:
Sub CreateNewFile()
Dim fs As Object
Set fs = CreateObject("Scripting.FileSystemObject")
'文件路径
Dim filePath As String
filePath = "C:\Path\To\Your\File.txt"
'创建文件
Set file = fs.CreateTextFile(filePath, True)
file.Close
MsgBox "File created successfully!"
End Sub
2. 读取文件内容:
Sub ReadFileContent()
Dim fs As Object
Set fs = CreateObject("Scripting.FileSystemObject")
'文件路径
Dim filePath As String
filePath = "C:\Path\To\Your\File.txt"
'打开文件
Dim file As Object
Set file = fs.OpenTextFile(filePath, 1)
'读取文件内容
Dim content As String
content = file.ReadAll
file.Close
MsgBox "File content: " & content
End Sub
操纵文件夹:
1. 创建新文件夹:
Sub CreateNewFolder()
Dim fs As Object
Set fs = CreateObject("Scripting.FileSystemObject")
'文件夹路径
Dim folderPath As String
folderPath = "C:\Path\To\Your\Folder"
'创建文件夹
fs.CreateFolder folderPath
MsgBox "Folder created successfully!"
End Sub
2. 列举文件夹中的文件:
Sub ListFilesInFolder()
Dim fs As Object
Set fs = CreateObject("Scripting.FileSystemObject")
'文件夹路径
Dim folderPath As String
folderPath = "C:\Path\To\Your\Folder"
'获取文件夹
Dim folder As Object
Set folder = fs.GetFolder(folderPath)
'列举文件
Dim file As Object
For Each file In folder.Files
MsgBox "File: " & file.Name
Next file
End Sub
这些示例演示了如何使用VBA操纵文件和文件夹。确保在使用这些代码时替换路径为你实际的路径。
转载请注明出处:http://www.zyzy.cn/article/detail/6696/VBA