繁体   English   中英

Excel vba 用于将单元格内容导出到 TXT 文件

[英]Excel vba for exporting cell content to TXT file

我有一个 Excel 文件( https://www.dropbox.com/s/hv9u68s136es190/Example2.xlsx?dl=0 ),在 A 列中包含所有人员,在名称文本(B 列)旁边的单元格中。 我想为每个人保存一个文本文件,其中包含名称旁边单元格中的文本。 文件名应该像人名一样被调用。 所以在这种情况下,我会有三个文本文件。 我不知道如何在 Excel 中使用 VBA 来管理它。 有人可以帮我弄这个吗?

在此处输入图片说明

请试试这个代码。 但是,您必须首先自己尝试一些东西。 我们通常帮助人们纠正他们的代码并学习...

文本文件将命名为 A 列中的人名。保存它们的文件夹将是保存活动工作表的工作簿之一。 当然,您可以根据需要定义它。

Option Explicit

Sub SaveTxtNamePlusTekst()
  Dim sh As Worksheet, lastR As Long, i As Long, strPath As String
  Set sh = ActiveSheet     ' use here the sheet you need
  strPath = sh.Parent.path 'you can define here the path you wish...
  If Dir(strpath, vbDirectory) = "" Then MsgBox "The folder path is not valid...": Exit Sub
  lastR = sh.Range("A" & Cells.Rows.Count).End(xlUp).row 'Last row in A:A
  For i = 2 To lastR
    'calling a Sub able to create a text file in a folder and put text in it
    WriteText sh.Range("A" & i).value, strPath, sh.Range("B" & i).value
  Next i
End Sub

Private Sub WriteText(strName As String, strPath As String, strText As String)
  Dim filePath As String
  filePath = strPath & "\" & strName & ".txt" 'building the txt file path
  FreeFile 1

    Open filePath For Output As #1
      Print #1, strText 'write the text
    Close #1
End Sub

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM