多次保存文件

时间:2019-01-17 11:57:54

标签: excel vba

我试图编写一个VBA脚本来编辑一些单元格,将excel电子表格另存为另一个名称和csv文件格式。我遇到的问题是重复此过程以保存多个excel文档。

我尝试使用While循环,但是我感觉一旦保存了第一个文档,它就会停止工作。该代码适用于第一个excel电子表格,但不会创建多个具有不同名称的文件。

Sub SaveFile()

Dim i As Integer
Dim c As Integer
Dim x As Integer

i = 1

x = InputBox("Enter the number of the Unit")
c = InputBox("How many Racks are in the Unit")

Do While i < c
If i < 10 Then
    Cells(2, 4).Value = x & "0" & i & "01"
    Cells(2, 6).Value = "RACK " & x & "0" & i & " /bal"
    ActiveWorkbook.SaveAs Filename:="C:\Test\" & x & "0" & i & ".csv", FileFormat:=xlCSV
    i = i + i
Else
    Cells(2, 4).Value = x & i & "01"
    Cells(2, 6).Value = "RACK " & x & i & " /bal"
    ActiveWorkbook.SaveAs Filename:="C:\Test\" & x & i & ".csv", FileFormat:=xlCSV
    i = i + i
End If
    i = c
Loop

End Sub

我希望它能创建多个电子表格文件,每个文件具有不同的值,并且每个文件的名称都不同,均为CSV格式。实际情况是,只有一个文档是由完美的值创建的。

1 个答案:

答案 0 :(得分:3)

我认为您正在寻找类似的东西:

Option Explicit

Public Sub SaveFile()
    Dim x As Long
    x = Application.InputBox(Prompt:="Enter the number of the Unit", Type:=1)

    Dim c As Long
    c = Application.InputBox(Prompt:="How many Racks are in the Unit", Type:=1)

    Dim i As Long
    For i = 1 to c
        Cells(2, 4).Value = x & Format$(i, "00") & "01"
        Cells(2, 6).Value = "RACK " & x & Format$(i, "00") & " /bal"
        ActiveWorkbook.SaveAs Filename:="C:\Test\" & x & Format$(i, "00") & ".csv", FileFormat:=xlCSV
    Next i
End Sub

请注意,我使用的是Application.InputBox method而不是InputBox function,因为在这里您可以指定类型Type:=1来强制用户输入数字。

此外,您无需检查i < 10而是只需检查Format$(i, "00")即可确保数字0的前导< 10

您可以使用For i = 1 to c循环,该循环会自动在i上递增Next i,因此您不需要递增i = i + 1

相关问题