Saving a Excel File into .txt format without quotes

前端 未结 8 855
攒了一身酷
攒了一身酷 2020-11-28 13:44

I have a excel sheet which has data in column A.There are many special characters in the cells.When I save the sheet in .txt format I get inverted commas at the start of eac

8条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-28 14:08

    I just spent the better part of an afternoon on this

    There are two common ways of writing to a file, the first being a direct file access "write" statement. This adds the quotes.

    The second is the "ActiveWorkbook.SaveAs" or "ActiveWorksheet.SaveAs" which both have the really bad side effect of changing the filename of the active workbook.

    The solution here is a hybrid of a few solutions I found online. It basically does this: 1) Copy selected cells to a new worksheet 2) Iterate through each cell one at a time and "print" it to the open file 3) Delete the temporary worksheet.

    The function works on the selected cells and takes in a string for a filename or prompts for a filename.

    Function SaveFile(myFolder As String) As String
    tempSheetName = "fileWrite_temp"
    SaveFile = "False"
    
    Dim FilePath As String
    Dim CellData As String
    Dim LastCol As Long
    Dim LastRow As Long
    
    Set myRange = Selection
    'myRange.Select
    Selection.Copy
    
    'Ask user for folder to save text file to.
    If myFolder = "prompt" Then
        myFolder = Application.GetSaveAsFilename(fileFilter:="XML Files (*.xml), *.xml, All Files (*), *")
    End If
    If myFolder = "False" Then
        End
    End If
    
    Open myFolder For Output As #2
    
    'This temporarily adds a sheet named "Test."
    Sheets.Add.Name = tempSheetName
    Sheets(tempSheetName).Select
    Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks _
        :=False, Transpose:=False
    
    LastCol = ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Column
    LastRow = ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Row
    
    For i = 1 To LastRow
        For j = 1 To LastCol
            CellData = CellData + Trim(ActiveCell(i, j).Value) + "   "
        Next j
    
        Print #2, CellData; " "
        CellData = ""
    
    Next i
    
    Close #2
    
    'Remove temporary sheet.
    Application.ScreenUpdating = False
    Application.DisplayAlerts = False
    ActiveWindow.SelectedSheets.Delete
    Application.DisplayAlerts = True
    Application.ScreenUpdating = True
    'Indicate save action.
    MsgBox "Text File Saved to: " & vbNewLine & myFolder
    SaveFile = myFolder
    

    End Function

提交回复
热议问题