我在 Access 中创建了一个数据库,用于存储有关我的工作的数据。
我还创建了一个链接到该数据库中的表的报告,该报告由宏运行,该宏通过 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://learn.microsoft.com/en-us/office/vba/api/access.docmd.outputto
感谢您提供使用路径位置保存此 pdf 文件的代码。 我在测试报告中做到了这一点,并且是第一次工作。 我遇到的问题是,如果我在创建第一个 pdf 文件后再次单击,则会出现错误“OutputTo 操作已取消”。并删除创建的第一个报告。 不确定问题是否出在我的系统设置上,或者您是否可以检查一下,我们将不胜感激。 谢谢 氯