我希望.txt file
为每个值创建一个column A
包含相应值的columns B and C
答案1
我越看越觉得这是一个很有用的小宏。为了防止它处理空白行(并锁定我的 Excel),我重写了代码,只在有可用数据时创建文件。此外,使用 而print
不是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
生成一个,并插入相应的信息.txt document
columns 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