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

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

细胞(1,3):

我得到了VBA,但我有一个问题。

我使用的VBA是将单元格(1,3)的内容保存在一行中 – '我得到了vba,但我有一个问题帮助我'我不希望它在一行中。

我的要求很简单。

  1. 我在工作表中有一个activexbutton。

  2. 当我点击button时,C列中的数据必须保存到包含换行符的.txt文件中。 所以如果单元格(1,3)有4行,单元格(2,3)有2行,那么.txt文件应该有6行。 .txt文件应该完全复制我的C列。

3.这个文本文件必须保存到“C”\ vbacodes \“path。

下面是我在网上find的这段代码

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 

首先更改path和文件名以符合您的要求,然后将此macros指定给一个button:

 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