首页 > 解决方案 > 循环在当前目录中创建的新文件夹中将范围保存为 pdf 文件

问题描述

我想将一系列 excel 表保存到当前目录中自动创建的新文件夹中的 pdf 文件中(我需要对文档中的所有 excel 表执行相同操作)但是每次运行代码时都没有保存文件或在我的桌面上创建的文件夹(我正在使用的 excel 文件位于桌面中)
我将不胜感激您的帮助谢谢这是我编写的函数

Sub PDF_saving()
    
    Dim tbAllBoxes() As Variant
        'Put all you textboxes into an array
        tbAllBoxes = Array(SuiviConso.Controls("Textbox2"), SuiviConso.Controls("Textbox3"), SuiviConso.Controls("Textbox4"), SuiviConso.Controls("Textbox5"), SuiviConso.Controls("Textbox6"), SuiviConso.Controls("Textbox7"), SuiviConso.Controls("Textbox8"), SuiviConso.Controls("Textbox9"))
        Dim tballLabels() As Variant
        tballLabels = Array(SuiviConso.Controls("Label2"), SuiviConso.Controls("Label3"), SuiviConso.Controls("Label4"), SuiviConso.Controls("Label5"), SuiviConso.Controls("Label6"), SuiviConso.Controls("Label7"), SuiviConso.Controls("Label8"), SuiviConso.Controls("Label9"))
        Dim shAllSheets As Variant
        'Put all your worksheets into an array
        shAllSheets = Array(ThisWorkbook.Sheets("sheet2"), ThisWorkbook.Sheets("sheet3"), ThisWorkbook.Sheets("sheet4"), ThisWorkbook.Sheets("sheet5"), ThisWorkbook.Sheets("sheet6"), ThisWorkbook.Sheets("sheet7"), ThisWorkbook.Sheets("sheet8"), ThisWorkbook.Sheets("sheet9"))
    
    Dim wbA As Workbook
    Dim lastrow2 As Integer
    Dim strPath, path  As String
    Dim filename As String
    Dim rng As Range
    
    
    For i = 1 To UBound(shAllSheets)
        If tbAllBoxes(i).Value <> "" Then
    filename = shAllSheets(i).Range("A1").Value & Format(Date, "MM-DD-YYYY") & " rapport de consommation " & ".pdf"
    strPath = path & filename
    MkDir strPath
    lastrow2 = shAllSheets(i).Range("A" & Rows.Count).End(xlUp).Row + 1
    Set rng = shAllSheets(i).Range("A1 : J" & lastrow2)
    rng.ExportAsFixedFormat Type:=xlTypePDF, filename:=ActiveWorkbook.path & filename
    End If
    Next i
    End Sub

标签: excelvbaloopspdf

解决方案


像这样的东西:

    Set FSO = CreateObject("scripting.filesystemobject")

    basepath = ActiveWorkbook.path & "/rapport de consommation/"

    For i = 1 To UBound(shAllSheets)
        
        filename = shAllSheets(i).Range("A1").Value
        folderPath = basepath & filename
        If Not FSO.folderexists(folderPath) Then FSO.createfolder (folderPath)
        
        With shAllSheets(i)
            .Range("A1:J" & .Cells(.Rows.Count, "A").End(xlUp).Row).ExportAsFixedFormat _
                                Type:=xlTypePDF, _
                                filename:=folderPath & "\" & filename & ".pdf"
        End With
    Next i

推荐阅读