VBA:读取和写入文本文件的行

时间:2017-06-14 12:49:15

标签: 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

1 个答案:

答案 0 :(得分:0)

我会从上到下将数据附加到文本文件中,但不会覆盖文本文件中已存在的数据。

'启动程序和子程序以编写VBA代码以将数据写入文本文件Append。

void Get (Book* bookPtr){
    Book mybook;
    switch(mybook.size = bookPtr->size){
    case 3: mybook.z = bookPtr->z;
    case 2: mybook.y = bookPtr->y;
    case 1: mybook.x = bookPtr->x;
            break;
    default:
        break;
    }
}