0



I have a macro which exports XLS to TXT and it works fine, except that the resulting TXT contains not only the useful data, but also empty lines below this data.

I may be mistaken, but looks like empty Excel cells are exported too. Is there a way to improve my code to export only those cells which have data?

Here's the link to the XLS file to be exported.

Here's the link to the resulting TXT file. Use keyboard arrow keys to see empty TABs below line #1, which contains useful data.

And here's the code:

Option Explicit

Sub Export_to_TXT_UTF16()

Dim saveas_filename As Variant
saveas_filename = Application.GetSaveAsFilename(FileFilter:="Unicode Text (*.txt), *.txt", Title:="SaveAs")
If saveas_filename = False Then
    Exit Sub
End If

With Application
    .ScreenUpdating = False
    .DisplayAlerts = False
End With

ActiveSheet.Copy

With ActiveSheet.UsedRange
    .Value = .Value
End With

Rows(1).Delete          'DELETE ROW #1

Columns("C:G").Delete       'DELETE COLUMNS C-G

ActiveWorkbook.SaveAs Filename:=saveas_filename, FileFormat:=xlUnicodeText

ActiveWorkbook.Close SaveChanges:=False

With Application
    .ScreenUpdating = True
    .DisplayAlerts = True
End With

MsgBox "Your data has been exported!", vbExclamation, "Sheet Exported"

End Sub
HexenSage
  • 117
  • 2
  • 10
  • Works fine for me. Are you sure those rows don't have invisible character (ex.: spaces) in some cells? – cybernetic.nomad Dec 16 '19 at 22:34
  • use `.Find` to find the last row as shown [HERE](https://stackoverflow.com/questions/11169445/error-in-finding-last-used-cell-in-excel-with-vba/11169920#11169920) What do you get? – Siddharth Rout Dec 17 '19 at 05:17
  • Guys, thank you for the input. I've uploaded the resulting file (link is in my initial post). If you look at it you will see what exactly the problem in TXT looks like. @Siddharth Rout - I tried to run the code you've shared, but i permanently have debug error. May i share my Excel file with you so that you can have a look at it? – HexenSage Dec 17 '19 at 17:57

1 Answers1

1

You may have non-printable characters, like spaces, or more likely carriage returns. Can you run the code below? Then re-run your code above and get back to me with the results.

Sub CleanUpData()
    Dim Ws As Worksheet
    Dim Rng As Range, Cell As Range
    Dim ArrCodes
    Dim i As Long

    Set Ws = ActiveSheet
    On Error Resume Next
    Set Rng = Ws.UsedRange.SpecialCells(xlConstants, xlNumbers + xlTextValues)
    If Rng Is Nothing Then
        Exit Sub
    End If
    On Error GoTo 0

    ArrCodes = Array(127, 129, 141, 143, 144, 157, 160)

    Application.ScreenUpdating = False
    Application.Calculation = xlCalculationManual

    For Each Cell In Rng
        'Use the CLEAN function to remove 32 non printing chracters (0 to 31)
        'Trim is for removing leading and trailing blanks
        Cell = Trim(WorksheetFunction.Clean(Cell))
        'Now remove character code 127, 129, 141, 143, 144, 157, 160
        For i = LBound(ArrCodes) To UBound(ArrCodes)
            Cell = Replace(Cell, Chr(ArrCodes(i)), "")
        Next i
    Next Cell

    Application.ScreenUpdating = True
    Application.Calculation = xlCalculationAutomatic
End Sub

As an alternative, this code will loop through all sheets and save each one as a separate text file. If you just want to save one single sheet as a text file, just don't run the loop, and active whatever single page you want to export as a flat file.

Sub SaveAllAsTextFile()

For Each xWs In Application.ActiveWorkbook.Worksheets
    xWs.Copy
    xTextFile = CurDir & "\temp_" & xWs.Name & ".txt"
    Application.ActiveWorkbook.SaveAs Filename:=xTextFile, FileFormat:=xlText
    Application.ActiveWorkbook.Saved = True
    Application.ActiveWorkbook.Close
Next

Dim shl As Object: Set shl = CreateObject("WScript.shell")
shl.CurrentDirectory = CurDir
shl.Run "cmd /C copy temp_*.txt " & ThisWorkbook.Name & ".txt" ' merge the temporary text files

'shl.Run "cmd /C del temp_*.txt" ' clean up the temporary text files


End Sub
ASH
  • 20,759
  • 19
  • 87
  • 200
  • Hi @ASH, thank you for this code. I did what you said (i suppose your code cleans empty spaces), but the resulting file is the same. :( I've added links to both - the XLS and the resulting TXT file to my initial post - could you please kindly have a look at them? Maybe the problem is that i have 2 sheets in 1 workbook? – HexenSage Dec 17 '19 at 18:11
  • I just ran your original code on your specific file and I saw no spaces at the end, no blank rows, nothing weird at all. Now, I ran this against a XML files named 'Sheet1' that I saw in the folder I downloaded from you. I didn't see any XLS files in that folder. – ASH Dec 17 '19 at 21:40
  • I just updated my original answer. Try this alternative. – ASH Dec 17 '19 at 21:51
  • I've run again the first ("cleaning") code from your post, then mine - nothing's changed. When i ran your 2nd code i got a "Run-time error 1004" which (based on debug) is caused by an Application.ActiveWorkbook.SaveAs Filename: line. However i want to be sure first we're talking about the SAME problem: when you download the TXT file from my initial post do you see empty lines below line #1 - with empty line #456 (!) being the last one? If you don't want to download file, just click on its name and it will be opened in browser. Use mouse to SELECT text and see empty lines i'm talking about. – HexenSage Dec 18 '19 at 10:00
  • Now look at the filesize: 10kb - d'u agree that's WAY too much for 1 line of text? I suppose this is caused exactly by those 455 empty lines. Now the question is: when you download my Excel file (from the initial post) and use my code from the post on YOUR machine - do you get the exported TXT file of the _same_ huge size with _same_ empty lines below line #1? If yes - this is not my local mistake, but the problem of the code (which was exactly the reason for my thread to appear here). – HexenSage Dec 18 '19 at 10:06