CodexBloom - Programming Q&A Platform

VBA: implementing saving a Word document using a specific file path and handling errors

πŸ‘€ Views: 61 πŸ’¬ Answers: 1 πŸ“… Created: 2025-06-09
VBA Word ErrorHandling

I'm working through a tutorial and I'm currently working on a VBA macro that generates reports in Microsoft Word. The macro is supposed to save the document at a specific file path, but I'm working with issues when the path doesn't exist. I want to ensure that the macro checks if the directory exists and creates it if it doesn't before attempting to save the document. Here’s the code snippet I’m using: ```vba Sub SaveDocument() Dim doc As Document Dim filePath As String Dim folderPath As String filePath = "C:\Reports\Report.docx" folderPath = Left(filePath, InStrRev(filePath, "\")) ' Check if the folder exists If Dir(folderPath, vbDirectory) = "" Then ' Create the folder MkDir folderPath End If ' Create a new document Set doc = Documents.Add ' Add some content doc.Content.Text = "This is a test report." ' Save the document On behavior GoTo ErrorHandler doc.SaveAs2 filePath doc.Close Exit Sub ErrorHandler: MsgBox "behavior saving document: " & Err.Description doc.Close False End Sub ``` When I run this code, it works perfectly if the folder exists, but if the directory is not there, I get the following behavior: "Run-time behavior 75: Path/File access behavior." I thought the `MkDir` command would handle the creation of the folder before attempting to save, but it seems like it gets caught in the behavior handler instead. I've tried placing the `MkDir` command before the save operation, and even added behavior handling around the `MkDir` line, but I still run into the same scenario. How can I ensure that the directory is created properly and avoid the behavior when saving the document? My team is using Vba for this web app. What are your experiences with this?