如何使用 VBA save/export 将 pdf 文件保存到特定文件夹

How to save/export a pdf to a certain folder using VBA

我在 Access 中创建了一个数据库,用于存储我的工作数据。

我还创建了一个链接到此数据库中的 table 的报告,该报告是 运行 通过宏创建的文件(导出)通过 VBA 到我的桌面.现在我正在尝试更改它,以便文件将检查目录(即桌面),如果未创建则创建一个年份文件夹(即 2020),然后在该文件夹中检查月份名称(即一月)如果是未创建,然后每个月创建一个日期文件夹等。现在这很好用。但是我正在努力让文件在完成这些检查后输出到这个位置。只是不确定在保持 DoCmd.OutputTo 等的同时如何表达它...这里有一些代码可以向您展示我的意思:

Function Reportmacro()
On Error GoTo Reportmacro_Err
   
    ' Check for year folder and create if needed
    If Len(Dir("H:TEST\" & Year(Date), vbDirectory)) = 0 Then
        MkDir "H:TEST\" & Year(Date)
    End If

     ' Check for month folder and create if needed
    If Len(Dir("H:TEST\" & Year(Date) & "\" & MonthName(Month(Date), False), vbDirectory)) = 0 Then
        MkDir "H:TEST\" & Year(Date) & "\" & MonthName(Month(Date), False)
    End If
    
    ' Check for day folder and create if needed
    If Len(Dir("H:TEST\" & Year(Date) & "\" & MonthName(Month(Date), False) & "\" & Day(Date), vbDirectory)) = 0 Then
        MkDir "H:TEST\" & Year(Date) & "\" & MonthName(Month(Date), False) & "\" & Day(Date)
        DoCmd.OutputTo acOutputReport, "Changeover Car Report", "PDFFormat(*.pdf)", "CCReport" & Day(Date) & "_" & Month(Date) & "_" & Year(Date) & ".pdf", False, "", , acExportQualityPrint
    End If
    
    
Reportmacro_Exit:
    Exit Function

Reportmacro_Err:
    MsgBox Error$
    Resume Reportmacro_Exit

End Function

目前它将转到“TEST”文件夹,但适用相同的逻辑。

试试这个,代码保持不变,只是在文件名中添加了文件夹路径:

Function Reportmacro()
On Error GoTo Reportmacro_Err

    Dim fPath as String
   
    ' Check for year folder and create if needed
    If Len(Dir("H:TEST\" & Year(Date), vbDirectory)) = 0 Then
        MkDir "H:TEST\" & Year(Date)
    End If

     ' Check for month folder and create if needed
    If Len(Dir("H:TEST\" & Year(Date) & "\" & MonthName(Month(Date), False), vbDirectory)) = 0 Then
        MkDir "H:TEST\" & Year(Date) & "\" & MonthName(Month(Date), False)
    End If
    
    ' Check for day folder and create if needed
    fPath = "H:TEST\" & Year(Date) & "\" & MonthName(Month(Date), False) & "\" & Day(Date)
    If Len(Dir(fPath, vbDirectory)) = 0 Then
        MkDir fPath
        DoCmd.OutputTo acOutputReport, "Changeover Car Report", "PDFFormat(*.pdf)", fPath & "\" & "CCReport" & Day(Date) & "_" & Month(Date) & "_" & Year(Date) & ".pdf", False, "", , acExportQualityPrint
    End If
    
    
Reportmacro_Exit:
    Exit Function

Reportmacro_Err:
    MsgBox Error$
    Resume Reportmacro_Exit

End Function

查看文档:https://docs.microsoft.com/en-us/office/vba/api/access.docmd.outputto