2017-06-14 50 views
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 
+0

您可能想查看SE代碼審查:https://codereview.stackexchange.com/堆棧溢出不是真的應該用於審查代碼。 – SaggingRufus

+0

根本不需要使用FSO,它內置了一些函數,可以很容易地用一些代碼E.g.將文件加載到數組中。 https://stackoverflow.com/a/11542133/246342 –

+0

您可以使用SaveSetting和GetSetting將設置保存在註冊表中https://msdn.microsoft.com/VBA/Language-Reference-VBA/articles/getsetting-function – Slai

回答

0

我會將數據附加到文本文件,從上到下,但不覆蓋文本文件中已存在的數據。

'啓動程序和子程序來編寫VBA代碼以將數據寫入文本文件追加。

Sub VBA_to_append_existing_text_file() 

'Declaring the strFile_Path variable as String Data Type to store the text file path. 
Dim strFile_Path As String 

'Assigning the Existing File path to the variable strFile_Path. 
strFile_Path = "C:\your_path_here\test.txt" 

'Opening the text file for Append with FileNumber as 1. 
Open strFile_Path For Append As #1 

'Writing to the sample text to the File using FileNumber and Write Command. 
YourValue = Worksheets("Sheet1").Range("A1").Value 
Write #1, YourValue 

'Closing the File using FileNumber. 
Close #1 

End Sub