Excel - 建立以包含其他儲存格資料的儲存格命名的文字文件

Excel - 建立以包含其他儲存格資料的儲存格命名的文字文件

我正在尋找.txt file為每個值創建一個column A包含相應值的columns B and C

答案1

我越看越發現它是一個有用的小宏。為了防止它處理空白行(並鎖定我的 Excel),我重寫了程式碼,僅在有可用資料時建立文件。此外,使用printnot 會write建立不含引號的文字。這是我用來完成同樣事情的方法。

Sub CreateFile()
Do While Not IsEmpty(ActiveCell.Offset(0, 1))
    MyFile = ActiveCell.Value & ".txt"
    'set and open file for output
    fnum = FreeFile()
    Open MyFile For Output As fnum
    'use Print when you want the string without quotation marks
    Print #fnum, ActiveCell.Offset(0, 1) & " " & ActiveCell.Offset(0, 2)
Close #fnum
ActiveCell.Offset(1, 0).Select
Loop
End Sub

請隨意使用和修改。感謝你這麼好的想法。

答案2

此巨集將取得 中的每個值,在值的名稱中column A產生 a並插入對應的訊息.txt documentcolumns B and C

Sub CreateTxt()
'
For Each ce In Range("A1:A" & Cells(Rows.Count, 1).End(xlDown).Row)
    Open ce & ".txt" For Output As #1
    Write #1, ce.Offset(0, 1) & " " & ce.Offset(0, 2)
    Close #1
Next ce
End Sub

四年後,我決定回到我的第一個 SU 問題 - 我剛開始接觸 VBA。這更好,但會覆蓋任何已存在的文件

Option Explicit

Sub CreateFileEachLine()

    Dim myPathTo As String
    myPathTo = "C:\Users\path\to\"
    Dim myFileSystemObject As Object
    Set myFileSystemObject = CreateObject("Scripting.FileSystemObject")
    Dim fileOut As Object
    Dim myFileName As String

    Dim lastRow As Long
    lastRow = Cells(Rows.Count, 1).End(xlUp).Row
    Dim i As Long

        For i = 1 To lastRow
            If Not IsEmpty(Cells(i, 1)) Then
                myFileName = myPathTo & Cells(i, 1) & ".txt"
                Set fileOut = myFileSystemObject.CreateTextFile(myFileName)
                fileOut.write Cells(i, 2) & "    " & Cells(i, 3)
                fileOut.Close
            End If
        Next

    Set myFileSystemObject = Nothing
    Set fileOut = Nothing
End Sub

相關內容