Few Suggestions
- Use Variables, Objects. Makes your life easier. :)
- Instead of
+
, use &
for concatenation.
- To
Bulk
write a range to text file, store it in an array and transpose it. This way no loop will be required.
- Avoid the loop to find the last row. You may want to see How to find the last row.
- When working with rows, avoid the use of
Integer
. Use Long
.
Is this what you are trying?
Option Explicit
Private Sub Exporter_Click()
Dim ws As Worksheet
Dim lRow As Long
Dim rng As Range
Dim FilePath As String
Dim fileName As String
'~~> Construct your path and filename
FilePath = "C:\Users\" & Environ("username") & "\Desktop\"
fileName = FilePath & "Résultats Pêchés.txt"
'~~> Set your worksheet
Set ws = ThisWorkbook.Sheets("Output")
With ws
'~~> Find last row in Col A
lRow = .Range("A" & .Rows.Count).End(xlUp).Row
'~~> Identify the range that you want to write to text
Set rng = .Range("A1:A" & lRow)
End With
Dim rngLines() As Variant
Dim output As Variant
'~~> Transfer the range value to a 2D array and join
rngLines = Application.Transpose(rng.Value)
output = Join(rngLines, vbCrLf)
'~~> Write to text file
Open fileName For Output As #1
Print #1, output
Close #1
'~~> Launch the file
Call Shell("Explorer.exe " & Chr(34) & fileName & Chr(34))
End Sub
EDIT
Thank you so much, I really appreciate it. How would I go about copying multiple columns? The data is going to be in the range of A1 to E last row. When I change the variable rng Set rng = .Range("A1:E" & lRow) to that, it gives me an error that there is an invalid procedure or argument. – WhiteStrips 6 mins ago
Is this what you want?
Option Explicit
Private Sub Exporter_Click()
Dim ws As Worksheet
Dim lRow As Long
Dim rng As Range
Dim FilePath As String
Dim fileName As String
'~~> Construct your path and filename
FilePath = "C:\Users\" & Environ("username") & "\Desktop\"
fileName = FilePath & "Résultats Pêchés.txt"
'~~> Set your worksheet
Set ws = ThisWorkbook.Sheets("Output")
With ws
'~~> Find last row in Col A
lRow = .Range("A" & .Rows.Count).End(xlUp).Row
'~~> Identify the range that you want to write to text
Set rng = .Range("A1:E" & lRow)
End With
Dim rw As Variant, col As Variant
Dim output As String
For Each rw In rng.Rows
For Each col In rng.Cells
output = output & col.Value & ","
Next col
output = output & vbNewLine
Next rw
'~~> Write to text file
Open fileName For Output As #1
Print #1, output
Close #1
'~~> Launch the file
Call Shell("Explorer.exe " & Chr(34) & fileName & Chr(34))
End Sub