我在B列中有要用作文件名的文本,并且要在C列中的相邻单元格中将这些内容添加到这些文件中。解决方案可能非常简单,但是我现在拥有的代码正在使用正确的名称创建文本文件,而实际上没有向文件中写入任何内容。
我几乎没有VBA经验,因此此代码100%基于我在该论坛上发现的内容
Sub CreateFiles()
Dim sExportFolder, sFN
Dim rName As Range
Dim action As Range
Dim oSH As Worksheet
Dim oFS As Object
Dim oTxt As Object
'sExportFolder = path to the folder you want to export to
'oSh = The sheet where your data is stored
sExportFolder = "H:\"
Set oSH = Sheet1
Set oFS = CreateObject("Scripting.Filesystemobject")
For Each rName In oSH.UsedRange.Columns("A").Cells
Set action = rName.Offset(, 1)
'Add .txt to the article name as a file name
sFN = rName.Value & ".txt"
Set oTxt = oFS.OpenTextFile(sExportFolder & "\" & sFN, 2, True)
oTxt.WriteLine action.Value
oTxt.Close
Next
答案 0 :(得分:1)
如果要在文件的 B 列中查找值,在 C 的列中查找值,这就是代码的外观:>
请在代码中设置您的工作表名称
Sub CreateFiles()
Dim sExportFolder As String, sFN As String
Dim oSH As Worksheet
Dim rName As Range
Dim oFS As Object, oTxt As Object
sExportFolder = "H:\"
Set oSH = ThisWorkbook.Sheets("Your Sheet Name Here") '<-- set sheet name here
Set oFS = CreateObject("Scripting.Filesystemobject")
For Each rName In oSH.Range("B1:B" & oSH.Cells(Rows.Count, 2).End(xlUp).Row)
If rName.Value <> "" Then
sFN = rName.Value & ".txt"
Set oTxt = oFS.OpenTextFile(sExportFolder & sFN, 2, True)
oTxt.WriteLine rName.Offset(0, 1)
oTxt.Close
End If
Next
End Sub
答案 1 :(得分:0)
Sub CreateFiles()
Dim sExportFolder, sFN
Dim rName As Range
Dim action As Range
Dim oSH As Worksheet
Dim oFS As Object
Dim oTxt As Object
'sExportFolder = path to the folder you want to export to
'oSh = The sheet where your data is stored
sExportFolder = "H:\"
Set oSH = Worksheets("Sheet1")
Set oFS = CreateObject("Scripting.Filesystemobject")
For Each rName In oSH.UsedRange.Columns("B").Cells
Set action = rName.Offset(, 1)
'Add .txt to the article name as a file name
sFN = rName.Value & ".txt"
Set oTxt = oFS.OpenTextFile(sExportFolder & "\" & sFN, 2, True)
oTxt.WriteLine action.Value
oTxt.Close
Next