2011年3月3日 星期四

開啟文字檔使用檔案系統物件(FileSystemObject)

'需要一個Command Button
Private Sub Command1_Click()

Dim objFile As Object
OpenFile objFile, "C:\123.txt", False, False
'參數1:File 物件,參數2:路徑+名稱,參考3:是否要覆蓋(參數4為True 才有作用),參數4:是否要建立新文字檔
' If Not objFile.AtEndOfLine Then
' MsgBox objFile.readall '全部讀出
' End If
Do While Not objFile.AtEndOfLine
MsgBox objFile.ReadLine '只讀取1行
Loop
End Sub


Public Function OpenFile(ByRef objFile As Object, _
ByVal FilePath As String, _
Optional OverWrite As Boolean = True, _
Optional blnCreate As Boolean = True) As Boolean
On Error GoTo ChkErr
Dim fso As Object
Set fso = CreateObject("Scripting.FileSystemObject")
If Not fso.FolderExists(Left(FilePath, InStrRev(FilePath, "\"))) Then
MsgBox "路徑不正確!", vbExclamation, "警告..."
OpenFile = False
Exit Function
End If

If fso.FileExists(FilePath) Then
'ReadOnly=1 是否為唯讀
If fso.GetFile(FilePath).Attributes = 1 Then
MsgBox "使用者沒有 " & FilePath & " 的使用權限", vbExclamation, "警告"
OpenFile = False
Exit Function
End If
End If
If blnCreate Then '建立
Set objFile = fso.CreateTextFile(FilePath, OverWrite)
Else '讀取
'ForReading
Set objFile = fso.OpenTextFile(FilePath, 1)
End If
OpenFile = True
Set fso = Nothing
Exit Function
ChkErr:
MsgBox Err.Number & "," & Err.Description
End Function

沒有留言:

張貼留言