I am new to VBA and have made necessary adjustments to a script I have found online. What I want to do is to get the values of the range G2:H40000
from an Excel file, with each row cell separated by a Tab, then saved to a UTF-8 text file.
I have tested the script for range G2:H12
, and it works. But when it involves 40,000+ row (like G2:H40000
) with each cell in column H containing many text, the script takes so long to finish that I had to stop the process after more than an hour.
How can I make the script below run faster and be more efficient?
Sub ExportToTxt()
Dim data As Range, row As Range, cell As Range
Dim output As String
Set data = Range("G2:H40000")
For Each row In data.Rows
For Each cell In row.Cells(1, 1) '1st param 1 excludes the table header
output = output & cell.Value & vbTab & cell.Offset(0, 1).Value ' Offset 2nd param gets the adjacent cell to its right
Next cell
output = output & vbNewLine
Next row
' Write to a UTF-8 encoded text file:
Filename = "C:\Users\lenovo\Desktop\output.txt"
Set fso = CreateObject("Scripting.FileSystemObject")
Set out = fso.CreateTextFile(Filename, True, True) 'Syntax: object.CreateTextFile(filename[,overwrite[,unicode]])
out.WriteLine (output)
out.Close
End Sub