如何将Excel工作表的特定列数据保存到.txt文件,包括每个单元格内容中的换行符

Raj*_*oti 0 excel vba excel-vba

我是VBA的新手。我有一个要求,我需要将Excel工作表的特定列中的数据(假设使用的C列数据的范围)保存到.txt文件。经过一些网页搜索后,我得到了VBA代码,但是问题是,如果一个单元格(例如Cell(1,3))的数据行多行,如下所示

单元格(1,3):

我获得了VBA,但遇到了问题。

我使用的VBA将cell(1,3)内容保存在一行中-'我得到了vba,但我有一个问题需要帮助''我不想将它放在一行中。

我的要求很简单。

  1. 我在工作表中有一个Activex按钮。

  2. 当我单击按钮时,C列中的数据必须保存到.txt文件中,包括换行符。因此,如果cell(1,3)有4行,而cell(2,3)有2行,那么.txt文件应该有6行。.txt文件应完全复制我的C列。

3.并且此文本文件必须保存到“ C” \ vbacodes \”路径。

以下是我在互联网上找到的这段代码

Private Sub CommandButton1_Click()
'Update 20130913Dim wb As Workbook
Dim saveFile As String
Dim WorkRng As Range
On Error Resume Next
xTitleId = "KutoolsforExcel"
Set WorkRng = Application.Selection
Set WorkRng = Application.InputBox("Range", xTitleId, WorkRng.Address, Type:=8)
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Set wb = Application.Workbooks.Add
WorkRng.Copy
wb.Worksheets(1).Paste
saveFile = Application.GetSaveAsFilename(fileFilter:="Text Files (*.txt), *.txt")
wb.SaveAs Filename:=saveFile, FileFormat:=xlText, CreateBackup:=False
wb.Close
Application.CutCopyMode = False
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
Run Code Online (Sandbox Code Playgroud)

Gar*_*ent 6

首先更改路径和文件名以符合您的要求,然后将此宏分配给按钮:

Sub TextFileMaker()

    Dim MyFilePath As String, MyFileName As String
    Dim N As Long, nFirstRow As Long, nLastrow As Long

    MyFilePath = "C:\TestFolder\"
    MyFileName = "whatever"
    Set fs = CreateObject("Scripting.FileSystemObject")
    Set a = fs.CreateTextFile(MyFilePath & MyFileName & ".txt", True)
    nLastrow = Cells(Rows.Count, "C").End(xlUp).Row
    nFirstRow = 1

    For N = nFirstRow To nLastrow
        t = Replace(Cells(N, "C").Text, Chr(10), vbCrLf)
        a.WriteLine (t)
    Next
    a.Close

End Sub
Run Code Online (Sandbox Code Playgroud)