我有 Excel 工作表想要将其保存为 txt 文件,但没有分隔符,同时将空单元格的空间保留在范围内
下面是代码
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/