getting VBA to Append txt from bottom to top
I would like to append a text (.txt) file backwards is this possible?
By backwards I mean writing text from bottom to top rather then the standards top to bottom.
Why because the txt file I want to compile is read so that items at the top of the list are given priority to those at th开发者_JAVA百科e bottom.
I can't think of any other way than to create a new file whenver you want to insert data at the top and then delete/rename the old one and rename the new file to the new one.
Not sure exactly your requirements BUT the easiest way in VBA is to 1. Add a reference to the Microsoft Scripting Runtime.
Public Sub Reverse()
Dim lReverseString As String
Dim lFSO As FileSystemObject
Set lFSO = New Scripting.FileSystemObject
With lFSO.OpenTextFile("SourceName", ForReading)
While Not .AtEndOfStream
' Note if you are looking to read a line at at a time use .ReadLine Instead of .Read
lReverseString = .Read & lReverseString
Wend
End With
' now you have a string in reverse
With lFSO.CreateTextFile("TargetName", True, False)
.Write lReverseString
.Close
End With
End Sub
This is a basic form which should get you going.
How about an array? It would not be suitable with a very large file:
Dim fs As Object
Dim ts As Object
Dim AllTextArray As Variant
''Late binding, no reference required
Set fs = CreateObject("Scripting.FileSystemObject")
''ForReading=1
Set ts = fs.OpenTextFile("c:\docs\BookX.csv", 1)
AllTextArray = Split(ts.ReadAll, vbCrLf)
For i = UBound(AllTextArray) To 0 Step -1
Debug.Print AllTextArray(i)
Next
If it's just writing each paragraph or sentence in the reverse order than it appears:
Sub Test()
Dim currentDocument As Document
Set currentDocument = ActiveDocument
Dim sourceDocument As Document
Set sourceDocument = Documents.Add("c:\words.txt")
Dim i As Long
For i = sourceDocument.Paragraphs.Count To 1 Step -1
currentDocument.Range.InsertAfter sourceDocument.Paragraphs(i).Range.Text
DoEvents
Next
sourceDocument.Close wdDoNotSaveChanges
End Sub
精彩评论