excel - 通过 Vba 循环保存 Excel 行

标签 excel vba

大家好,我想将 Excel 文件的每一行保存为批处理文件。 我对第二行做了它,但不能在循环中执行它。

Sub ExportFile()

Dim objFSO, objFile
Dim fileName As String
Dim RootPath As String
Dim text_comm As String
Dim OutputString: OutputString = ""

fileName = Cells([2], [1])
text_comm = Cells([2], [5])
RootPath = "C:\Users\DELL\Desktop\PDM SOLID DOSYA YOLU\"

Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile = objFSO.CreateTextFile(RootPath + fileName + ".bat")

Do
OutputString = OutputString & Replace((text_comm), Chr(10), vbNewLine) & vbNewLine
objFile.Write (OutputString)
fileName = Cells([2] + 1, [1]) #Wrong
text_comm = Cells([2] + 1, [5]) #Wrong
Loop Until IsEmpty(text_comm)

Set objFile = Nothing
Set objFSO = Nothing

End Sub

最佳答案

将单元格内容导出为文本文件

  • 假设第一列(“A”)包含文件基本名称,第五列(“E”)包含代码(每个代码位于一个单元格中)。
Option Explicit

Sub ExportFiles()
    
    Const RootPath As String = "C:\Users\DELL\Desktop\PDM SOLID DOSYA YOLU\"
    Const FirstRow As Long = 2
    Const NameCol As Long = 1
    Const CodeCol As Long = 5
    
    Dim ws As Worksheet: Set ws = ActiveSheet ' improve!
    
    Dim r As Long: r = FirstRow
    Dim FileBaseName As String: FileBaseName = ws.Cells(r, NameCol)
    Dim text_comm As String: text_comm = ws.Cells(r, CodeCol)
    
    Dim fso As Object: Set fso = CreateObject("Scripting.FileSystemObject")
    Dim fsoFile As Object
    Dim OutputString As String
    
    Do Until Len(text_comm) = 0
        Set fsoFile = fso.CreateTextFile(RootPath & FileBaseName & ".bat")
        OutputString = Replace(text_comm, Chr(10), vbNewLine) & vbNewLine
        fsoFile.Write OutputString
        r = r + 1
        FileBaseName = ws.Cells(r, NameCol)
        text_comm = ws.Cells(r, CodeCol)
    Loop

    MsgBox "Files created.", vbInformation

End Sub

关于excel - 通过 Vba 循环保存 Excel 行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/71478920/

相关文章:

java - 在java中写入剪贴板和excel导出链接

vba - 在另一个工作表中显示隐藏列

vba - 比较 object.Value = Null 不会产生预期的结果

regex - 如何仅捕获匹配字符串的一部分?非捕获组

vba - CreatePivotTable() 上的奇怪/不稳定行为

excel - 使用公式标准引用外部工作簿中的命名范围

excel - 是否有用于创建 Excel 电子表格的通用 Lisp 库?

vba - Excel VBA 将数据从一个单元格转换为行(类型不匹配错误)

vba - 全屏编码

Excel VBA 在数字字符串中添加零