1
我設法將讀取或寫入文本文件中的行的函數一起破解。我正在使用它來保存我的應用程序的一些設置。只想看看每個人的輸入,看看是否有更好的方式來編輯文本文件中的一行。特別是構建數組以編輯行的部分。這是我的。VBA:讀取和寫入文本文件的行
Public ReadOptionsOutput As String
Public FSO As New FileSystemObject
Public TxtFileOutPut As String
Public Function TxtFile(WritetoFile As Boolean, FileDir As String, line As
Variant, What As String)
Dim FileContent() As Variant
Dim Idx As Integer
Dim Txtstream As Object
'////////////////Write to file///////////////
If WritetoFile = True Then
Set Txtstream = FSO.OpenTextFile(FileDir, ForReading, False)
Idx = 0
On Error GoTo Err1 'To catch the last blank line. Dont see another way to
see if .ReadLine is blank
Do 'Build an array to edit lines in Text file
Idx = Idx + 1
ReDim Preserve FileContent(1 To Idx)
FileContent(Idx) = Txtstream.ReadLine
Loop
Err1:
Open FileDir For Output As #1: Close #1 'Delet all text inside of File
Set Txtstream = Nothing
Set Txtstream = FSO.OpenTextFile(FileDir, ForAppending, False)
FileContent(line) = What 'Edit line in the array
For Idx = 1 To Idx - 1
Txtstream.WriteLine (FileContent(Idx)) 'Write everything back to
textfile
Next
'/////////////////////Read file///////////////
ElseIf WritetoFile = False Then 'Reads Line in file only
Set Txtstream = FSO.OpenTextFile(FileDir, ForReading, False)
NextLine = 1
Do 'Loop thru to selected line and read it
TxtLine = Txtstream.ReadLine
If NextLine = line Then
TxtFileOutPut = TxtLine
End If
NextLine = NextLine + 1
Loop Until NextLine > line
End If
Txtstream.Close
End Function
您可能想查看SE代碼審查:https://codereview.stackexchange.com/堆棧溢出不是真的應該用於審查代碼。 – SaggingRufus
根本不需要使用FSO,它內置了一些函數,可以很容易地用一些代碼E.g.將文件加載到數組中。 https://stackoverflow.com/a/11542133/246342 –
您可以使用SaveSetting和GetSetting將設置保存在註冊表中https://msdn.microsoft.com/VBA/Language-Reference-VBA/articles/getsetting-function – Slai