简体   繁体   English

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

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

I have an Excel file ( https://www.dropbox.com/s/hv9u68s136es190/Example2.xlsx?dl=0 ) with in column A all the persons and in the cell next to there name text (column B).我有一个 Excel 文件( https://www.dropbox.com/s/hv9u68s136es190/Example2.xlsx?dl=0 ),在 A 列中包含所有人员,在名称文本(B 列)旁边的单元格中。 I want to save for every person a text file containing the text in the cell next to there name.我想为每个人保存一个文本文件,其中包含名称旁边单元格中的文本。 The filename should be called like the persons name.文件名应该像人名一样被调用。 So in this case i would have three text files.所以在这种情况下,我会有三个文本文件。 I do not know how to manage this using VBA in Excel.我不知道如何在 Excel 中使用 VBA 来管理它。 Can someone help me with this?有人可以帮我弄这个吗?

在此处输入图片说明

Try this code, please.请试试这个代码。 But, you must initially try something on your own.但是,您必须首先自己尝试一些东西。 We usually help people correct their code and learn...我们通常帮助人们纠正他们的代码并学习...

The text files will be named like the people names in column A. The folder where they will be saved will be the one of the workbook which keeps the active sheet.文本文件将命名为 A 列中的人名。保存它们的文件夹将是保存活动工作表的工作簿之一。 You can define it as you need, of course.当然,您可以根据需要定义它。

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