gpt4 book ai didi

excel - 通过 Vba 循环保存 Excel 行

转载 作者:行者123 更新时间:2023-12-04 20:08:09 25 4
gpt4 key购买 nike

大家好,我想将我的 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/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com