1.創建一個類,命名爲:myfile ,複製下面代碼進去
'判斷文件是否存在
Public Function isFileExis(path As String) As Boolean
If Dir(path, vbDirectory) = "" Then
'不存在
isFileExis = False
Else
'存在
isFileExis = True
End If
End Function
'作用:根據路徑逐級創建文件夾
'參數: path 路徑 f:\文件夾a\文件夾b
'返回: 無;
Public Function createFolder(path As String) 'C:\Users\Administrator\Desktop\類操作 '\\A352337697\d\My Documents
Dim arr, a, temPath As String, n
arr = Split(path, "\")
For a = 0 To UBound(arr)
temPath = temPath & arr(a) & "\"
If Len(arr(a)) > 0 Then
n = n + 1
If n > 1 Then
'MsgBox temPath & "_________" & isFileExis(temPath)
If isFileExis(temPath) = False Then
MkDir temPath
End If
End If
End If
Next a
End Function
'作用: 寫入文件內容,如果文件不存在,則逐級創建出路徑,直到創建此路徑的文件,再寫入
Public Function writeFile(path As String, content As String)
'MsgBox path
'//取得文件所在路徑
Dim fPath As String
fPath = Replace(path, "\" & Split(path, "\")(UBound(Split(path, "\"))), "")
'//生成文件夾路徑
Call createFolder(fPath)
'MsgBox fPath
'//生成文件
'//寫入
Open path For Output As #1
Print #1, content;
Close #1
End Function
'作用: 寫入文件內容,如果文件不存在,則逐級創建出路徑,直到創建此路徑的文件,再寫入
Public Function writeFileAppend(path As String, content As String)
'MsgBox path
'//取得文件所在路徑
Dim fPath As String
fPath = Replace(path, "\" & Split(path, "\")(UBound(Split(path, "\"))), "")
'//生成文件夾路徑
Call createFolder(fPath)
'MsgBox fPath
'//生成文件
'//寫入
Open path For Append As #1
Print #1, content;
Close #1
End Function
'作用: 讀取文件內容,如果文件不存在,則逐級創建出路徑,直到創建此路徑的文件,再讀取
'參數:path
'返回:文件內容;
Public Function readFile(path As String)
'MsgBox path
'//取得文件所在路徑
Dim fPath As String
fPath = Replace(path, "\" & Split(path, "\")(UBound(Split(path, "\"))), "")
'//生成文件夾路徑
Call createFolder(fPath)
'MsgBox fPath
'//生成文件
Open path For Output As #1
Print #1, "";
Close #1
'//讀取
Open path For Input As #1
readFile = StrConv(InputB$(LOF(1), 1), vbUnicode)
Close #1
End Function
2.然後可以這樣調用
Private Sub Command1_Click()
Dim ff As myfile '搜索'聲明類
Set ff = New myfile '實例化..這樣就可以使用這個類了
Call ff.writeFileAppend("f:\臨時文件夾\真的嗎\不要緊吧.txt", "真的嗎") '調用這個實例的方法
Set ff = Nothing '釋放對象
End Sub