How to Write a VBA Code to Save & Send a Word Document Via Email
- 1). Open Microsoft Word on an empty document. Click on "Developer" from the menu across the top of the screen. When you do this, a new option appears in the second row of menu items titled "Visual Basic." Click on this.
- 2). Decide on what you will call your new macro. For this example, name it "SaveSend" by typing this line on the coding screen that opened when you clicked on Visual Basic:
Sub SaveSend() - 3). Add a comment to explain what the macro will do by typing this under the preceding line:
'
' This will prompt me for a folder and document file name to save
' and then open a window to email the document as an attachment.
'
Note: You can break this into several lines of comment, which will not affect the macro by prefacing each line with an apostrophe. The ' mark is absolutely important; otherwise, the macro will fail when it tries to execute those lines. The extra ones on blank lines set off the comment from the code. - 4). Create the actual macro by typing the lines of code below after the last apostrophe However, starting with the line beginning "ActiveDocument.SaveAs" and ending with the "SaveAsAOCELetter:=False" do not press the "Enter" key to create a new line; keep typing all in one string. Alternatively, use an underscore ( _ ) to break the lines for readability. Visual Basic ignores this character.
Dim whatfolder, whatfile As String
whatfolder = InputBox("Save doc in what folder? Do not enter the Drive name.")
whatfile = InputBox("Save doc under what file name?")
ChangeFileOpenDirectory "C:\" & whatfolder
ActiveDocument.SaveAs filename:=whatfile & ".docx", FileFormat:= wdFormatXMLDocument, LockComments:=False, Password:="", AddToRecentFiles:=True, WritePassword:="", ReadOnlyRecommended:=False, EmbedTrueTypeFonts:=False, SaveNativePictureFormat:=False, SaveFormsData:=False, SaveAsAOCELetter:=False
ActiveDocument.SendMail
End Sub - 5). Enter some text within the Word document you have open or create a new Word document. Click on "Developer" again, but this time click on "Macros" when the second line of menu options appears. It will be next to the Visual Basic link. You should see the new macro listed. Click on it and then on "Run." The macro should prompt you for a folder and file name and then open a Microsoft Outlook window to enter the addressee. The document will already be attached.
- 6). Check the macro if it does not work by comparing the code you just entered.
As an alternative, click on the Macro again and "Step Into" instead of "Run." Press "F8" to step through the macro to find where the error is located.
Source...