简体   繁体   中英

vba define range ending text

I'm trying to process a data file and export each section to a separate text file. I can specify a range to export without issue (A1:A58) but I never know how many lines I'll need so it should be dynamic. For example, sheet1 will export 58 rows because row 1 will always start the range (A1) and 58 (A58) contains the text "Referring" indicating the end of that record. Then, those rows will be deleted. The next record will start with specific text "NewRecord" (A1) and complete with the words "Referring" again.

Sub ExportRange()
Dim c As Range, r As Range
Dim output As String
Dim MyFolder As String
Dim MyFile As String
Dim i As Long
Dim MyOldFile As String
Dim MyNewFile As String
MyFolder = "C:\Users\profile\Documents\test"
MyFile = Dir(MyFolder & "\text.txt")
i = i + 1
MyOldFile = MyFolder & "\" & MyFile
MyNewFile = MyFolder & "\" & Sheets("Sheet1").Range("B20") & "_" & i & ".txt"
For Each r In Range("A1:A37").Rows
    For Each c In r.Cells
        output = output & "," & c.Value
        Next c
    output = output & vbNewLine
Next r
Open "C:\Users\profile\Documents\test\Text.txt" For Output As #1
Print #1, output
Close
Name MyOldFile As MyNewFile
MyFile = Dir
Close
End Sub

This will find the first row that contains "Referring" searching from the top down and create a range from it that is used in the For loop.

Sub ExportRange()
Dim c As Range, r As Range, LoopRange as Range
Dim output As String
Dim MyFolder As String
Dim MyFile As String
Dim i As Long
Dim MyOldFile As String
Dim MyNewFile As String
Set LoopRange = Range("A1", Cells(Range("A:A").Find(what:="Referring", after:=Range("A1"), searchdirection:=xlNext).Row, "A"))
MyFolder = "C:\Users\profile\Documents\test"
MyFile = Dir(MyFolder & "\text.txt")
i = i + 1
MyOldFile = MyFolder & "\" & MyFile
MyNewFile = MyFolder & "\" & Sheets("Sheet1").Range("B20") & "_" & i & ".txt"
For Each r In LoopRange.Rows
    For Each c In r.Cells
        output = output & "," & c.Value
        Next c
    output = output & vbNewLine
Next r
Open "C:\Users\profile\Documents\test\Text.txt" For Output As #1
Print #1, output
Close
Name MyOldFile As MyNewFile
MyFile = Dir
Close
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM