excel - 将 Excel 文件另存为不带分隔符的文本并保留空单元格

标签 excel vba

我有 Excel 工作表想要将其保存为 txt 文件,但没有分隔符,同时将空单元格的空间保留在范围内

enter image description here

the desired output

下面是代码

    Dim WorkRng As Range
Dim xFile As Variant
Dim xFileString As String
On Error Resume Next
xTitleId = "Define Range"
Set WorkRng = Application.Selection
Set WorkRng = Application.InputBox("Range", xTitleId, WorkRng.Address, Type:=8)
Application.ActiveSheet.Copy
Application.ActiveSheet.Cells.Clear
WorkRng.Copy Application.ActiveSheet.Range("A1")
Set xFile = CreateObject("Scripting.FileSystemObject")



xFileString = Application.GetSaveAsFilename("") 'fileFilter:="Comma Separated Text (*.CSV), *.CSV")
Application.ActiveWorkbook.SaveAs Filename:=xFileString & ".txt", FileFormat:=xlText, CreateBackup:=False
End Sub

最佳答案

请尝试下一个代码。它假设在图片中看起来空的单元格中没有任何空间,它们只是空的:

Sub testSaveAsTextNoDelim()
   Dim fileSaveName As String, fileNam As String, TempNam As String
   Dim fso As Object, txtStr As Object, Fileout As Object, strText As String

   fileNam = "textWithoutDelim.txt" 'the name you want for the txt file
   fileSaveName = Application.GetSaveAsFilename(InitialFileName:=fileNam, _
                                 Filefilter:="Text Files (*.txt), *.txt")

    If fileSaveName <> "" Then
        'create a temporary name for a text file to be processed:
        TempNam = left(fileSaveName, Len(fileSaveName) - 4) & "1.txt"
        ActiveWorkbook.SaveAs fileName:=TempNam, FileFormat:=xlTextMSDOS  'xlTextWindows

        Set fso = CreateObject("Scripting.FileSystemObject")

        Set txtStr = fso.OpenTextFile(TempNam)
            strText = txtStr.ReadAll 'read all the content in a string variable
        txtStr.Close
        strText = Replace(strText, vbTab & vbTab, " ")'replace double Tab with space " "
        strText = Replace(strText, " " & vbTab, "  ") 'replace Tab and " " with double spaces
        strText = Replace(strText, vbTab, "") 'replace all Tabs
        'drop the processed string in the file you need:
        Set Fileout = fso.CreateTextFile(fileSaveName, True, True)
            Fileout.Write strText
        Fileout.Close
        'here you can close the created workbook and Kill the file...
        MsgBox "Saved as " & fileSaveName
    End If
End Sub

关于excel - 将 Excel 文件另存为不带分隔符的文本并保留空单元格,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62168380/

相关文章:

java - 如何使用poi从excel表中检索百分比类型的值

excel - 在 VBA 中使用 Excel 中的公式创建函数

excel - 每 5 行隐藏 4 个

vba - 在 VBA 中对多个键进行排序;运行时错误 450 : Wrong number of arguments or invalid property assignment

excel - VBA-Excel 如何清除 ComboBox 项目

excel - Apache POI : delete the cached results from the file

VBA 文本到列读取美国日期格式

vba - Excel VBA将参数传递给OLEDBConnection

sql - 用于显示来自(Mysql 数据库)的数据的 Excel 插件

VBA vlookup 与 excel 事件