簡體   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