Word VBA: Choose template from Dialog for a new Document - vba

My macro will create a new document based on an existing template:
Documents.Add Template:=strTemplateName, NewTemplate:=False, DocumentType:=0
I'd like the user to be able to select the template "strTemplateName" from a dialog box, but I'm not even sure if you can capture its name with the Dialogs property. And would you use wdDialogToolsTemplates or wdDialogFileOpen?

The easiest way to answer your second question,
would you use wdDialogToolsTemplates or wdDialogFileOpen?
Is to simply try both and see which one suits you better. Good old fashioned trial and error FTW :)
I don't think the either is what you want, actually. I would probably just use a normal FileDialog dialog.
Try this:
Sub test()
Dim dialog As FileDialog
Dim strTemplateName as String
Set dialog = Application.FileDialog(msoFileDialogFilePicker)
dialog.AllowMultiSelect = False
dialog.Show
If dialog.SelectedItems.Count = 1 Then
strTemplateName = dialog.SelectedItems(1)
Else:
MsgBox "no file selected!", vbInformation
Exit Sub
End If
Documents.Add Template:=strTemplateName, NewTemplate:=False, DocumentType:=0
End Sub

Related

How to search and replace across multiple word documents in the same folder?

I've tried to use the below code which I found on this conversation How To Search And Replace Across Multiple Files In Word? supplied by Charles Kenyon. However, it doesn't seem to work for me. I've enabled macros on my word and added the below code as a new module in Macros. When I go to replace all, it'll replace the text as per normal, but after doing this, when I open up the other macros enabled word doc, I find that the same text is still in these docs, without being replaced. Am I doing something wrong? Namely, I also wish to add a wildcard entry into my replace all, will the below code work or can someone suggest a better alternative? I have tested the below code with and without wildcard entries to no avail. I've also tried the code on this page in my macros but it also didn't work How to find and replace a text in multiple Word documents using VBAThanks for any help!
Option Explicit
Public Sub BatchReplaceAll()
Dim FirstLoop As Boolean
Dim myFile As String
Dim PathToUse As String
Dim myDoc As Document
Dim Response As Long
PathToUse = "C:\Test\"
'Error handler to handle error generated whenever
'the FindReplace dialog is closed
On Error Resume Next
'Close all open documents before beginning
Documents.Close SaveChanges:=wdPromptToSaveChanges
'Boolean expression to test whether first loop
'This is used so that the FindReplace dialog will
'only be displayed for the first document
FirstLoop = True
'Set the directory and type of file to batch process
myFile = Dir$(PathToUse & "*.doc")
While myFile <> ""
'Open document
Set myDoc = Documents.Open(PathToUse & myFile)
If FirstLoop Then
'Display dialog on first loop only
Dialogs(wdDialogEditReplace).Show
FirstLoop = False
Response = MsgBox("Do you want to process " & _
"the rest of the files in this folder", vbYesNo)
If Response = vbNo Then Exit Sub
Else
'On subsequent loops (files), a ReplaceAll is
'executed with the original settings and without
'displaying the dialog box again
With Dialogs(wdDialogEditReplace)
.ReplaceAll = 1
.Execute
End With
End If
'Close the modified document after saving changes
myDoc.Close SaveChanges:=wdSaveChanges
'Next file in folder
myFile = Dir$()
Wend
End Sub

My access to word merge code is not working

I have made a form in access and I'm trying to code a "merge to word" button but my code has a problem and I dont know how to fix it.
Here's the code:
Private Sub Command102_Click()
Dim LWordDoc As String
Dim oApp As Object
'Path to the word document
LWordDoc = "C:\school\information tech\document.docx"
If Dir(LWordDoc) = "" Then
MsgBox "Document not found."
Else
'Create an instance of MS Word
Set oApp = CreateObject(Class:="Word.Application")
oApp.Visible = True
'Open the Document
oApp.Documents.Open FileName:=Document.docx
End If
End Sub
If someone could help that would be great. Ill attach screenshots of the error I get when I click the button and the code as the debugger is pointing to the problem. (pointing to the start of the "oApp.Documents.Open FileName:=Document.docx" line)
Thanks heaps
Since you create a variable to hold the filename, try using that:
oApp.Documents.Open FileName:=LWordDoc

Open a Word 2013 legacy Open dialog in a specific folder

I have a simple Word macro that shows the legacy Open dialog.
Sub LegacyOpen()
DoEvents
Dialogs(wdDialogFileOpen).Show
End Sub
I’m now trying to get it to open in a specific folder.
"C:\Users\Paul Schroeter\Documents\Microsoft Word Documents".
After about an hour I have not found an macro argument or example of how to get it to do what I want it to do.
If you wonder why I need to do this, it’s because every time I use “Search documents” in the legacy Open dialog, it resets the Open dialog path to "C:\Users\Paul Schroeter\Documents", which is driving me insane, because I then have to change it back to the folder where I actually keep my Word documents.
A number of the built-in Word dialog boxes have "dialog box arguments" corresponding to some of the controls/settings in the dialog box. A list can be found here. These are not part of the Intellisense and are late-bound into the object model. The developer needs to know they exist and how to look them up and use them.
One of these built-in arguments is to set/read the file full name from the File/Open dialog box. In VBA the arguments are usually used in a With block. Putting the argument before the Show or Display method executes the setting before the dialog box is shown to the user. If it's placed after the method, then it's used to read the user's choice.
Sub WordFileOpen()
Dim dlg As Word.Dialog
Dim sPath As String
Set dlg = Application.Dialogs(wdDialogFileOpen)
sPath = "C:\Users\Paul Schroeter\Documents\Microsoft Word Documents"
With dlg
.Name = sPath
.Show
End With
End Sub
If you consider something different than Dialogs collection you could use FileDialogs property. Here is working example:
Sub OtherWindowType()
Dim FD As FileDialog
Set FD = Application.FileDialog(msoFileDialogFilePicker)
With FD
.AllowMultiSelect = False
.InitialFileName = "c:\" '...your path here
.Show
End With
'if you want to open the file...
If FD.SelectedItems.Count > 0 Then
Documents.Open FD.SelectedItems(1)
End If
End Sub

Save Excel Sheet text only to text file VBA

I am trying to copy the values of one column in a sheet to a text file. The code I currently have causes runtime error 434.
Sheets("Output to fcf.1").Columns("A").SaveToText "P:\4_Calcs\02. Flag Mapping\test_.txt"
If I try and save the whole sheet
Sheets("Output to fcf.2").SaveToText "P:\Clear Project Drive\CLE10276 AWS SMP Model Assessmnts\4_Calcs\02. Flag Mapping\test2_.txt"
I get the entire sheet converted into text rather than just the text in the sheet. Is there a simple way to do this?
Thanks in advance!
Not sure which Excel version you have but I don't see a method for SaveToText.
But this procedure should work, or at least get you started...
Sub SaveColumn(sheetName As String, columnName As String, fileName As String)
Dim cell
Dim fso
Dim file
Set fso = CreateObject("Scripting.FileSystemObject")
Set file = fso.CreateTextFile(fileName, True)
For Each cell In Sheets(sheetName).Columns(columnName).Cells
If cell.Value <> "" Then
file.WriteLine cell.Value
End If
Next
file.Close
Set file = Nothing
Set fso = Nothing
End Sub
To call it...
SaveColumn "Output to fcf.1", "A", "P:\4_Calcs\02. Flag Mapping\test_.txt"
This is designed to be used as a macro.
Step by step guide:
1) From excel, hit Alt+F11 on your keyboard.
2) From the menu bar, click Insert, then Module
3) Copy and paste the code provided below into the new module that opens.
NOTE: DocPath = "C:\docs\data.txt" should be wherever you want the output file saved, including the file's actual name. Remember, the folder you want the output file to be located in should ALREADY exist. This does not create the folder if it can't be found.
4) From the menu bar, click Tools, then References. Make sure both "Microsoft Office 14.0 Object Library" as well as "Microsoft Word 14.0 Object Library" are checked, and hit okay (See screenshot for details)
5) Save the document as an .xlsm file (This file type supports Macros)
6) Close the VBA editor. Back in Excel, on the ribbon click View and then Macros. Your new macro should be in the list as ExportToTXT
7) Select it and hit run.
Sub ExportToTXT()
Dim DocPath As String
Dim MsgBoxCompleted
Columns("A").Select
Dim AppWord As Word.Application
Set AppWord = CreateObject("Word.Application")
AppWord.Visible = False
Selection.Copy
DocPath = "C:\docs\data.txt"
'Create and save txt file
AppWord.Documents.Add
AppWord.Selection.Paste
AppWord.ActiveDocument.SaveAs2 Filename:=DocPath, FileFormat:=wdFormatText
Application.CutCopyMode = False
AppWord.Quit (wdDoNotSaveChanges)
Set AppWord = Nothing
MsgBoxCompleted = MsgBox("Process complete.", vbOKOnly, "Process complete")
End Sub
Good luck, and if you have any questions, don't hesitate to ask.
NOTE: These directions might seem overly simplified for your skill level, but I wrote the answer like this to potentially help others in the future.
EDIT
Change
DocPath = "C:\docs\data.txt"
to
DocPath = "C:\docs\data.fcf"
And change
AppWord.ActiveDocument.SaveAs2 Filename:=DocPath, FileFormat:=wdFormatText
to
AppWord.ActiveDocument.SaveAs2 Filename:=DocPath
The output file will be .fcf format. Whether or not it will open properly is something I'm not sure of. You'd have to test in the program you're using.

MS Access 2010 - How can I tie an entry text box to a VBA command that opens a MS Word file based on user's entry?

Option Compare Database
Function Openword(conPath As String)
Dim appword As Word.Application
Dim doc As Word.Document
On Error Resume Next
Error.Clear
Set appword = GetObject(, "word.application")
If Err.Number <> 0 Then
Set appword = New Word.Application
appword.Visible = True
End If
Set doc = appword.Documents.Open(conPath, , True)
appword.Activate
Set doc = Nothing
Set appword = Nothing
End Function
Private Sub Command5_Click()
Dim mydoc As String
mydoc = "J:\3 - Client Services\1-Programs\12229709.docx"
Call Openword(mydoc)
End Sub
So far I have made the code that will open a specific file when the button on the form is clicked. However, there are a ton of these files that the user needs to be able to select and open. To keep it simple, I want them to be able to open the Word file by simply typing in the name of the file and clicking a button that will find and open it. The name of the file in the example above is simply 12229709.docx, but there are other files similar to it (e.g. 12172029, 12124057...) all in the same location. I want there to be a text box where the user can enter in the number and the button will check that specific folder for a file name with that number in it (without having to add the ".docx" if possible). How do I go about doing this?
EDIT - I forgot to mention that I cannot show the file path or use a file dialog box to allow the user to pick the file because the users that will be choosing the file do not have authorization to access this part of the network.
Try this out
Dim MyValue as Variant
MyValue = Inputbox("Enter File Name")
Dim MyDoc as String
MyDoc = "J:\3 - Client Services\1-Programs\" & MyValue & ".docx"
Call OpenWord(MyDoc)
Not sure if that is what you are looking for but I hope it helps.
I don't know why you'd want to make your user type in a file name when you can just open a file dialog and have them click on the right file.
Just put a command button on your form and include a line "Application.FollowHyperlink" plus this function name. The computer file associations can take care of the rest.
Sub Command()
Application.FollowHyperlink FileName()
End Sub
Public Function FileName() As String
Dim f As Object
' Must have object reference set to a MS Office Object Library for this to work.
Set f = Application.FileDialog(msoFileDialogFilePicker)
With f
.AllowMultiSelect = False
If .Show = -1 Then
FileName = .SelectedItems(1)
End If
End With
FileName = Nz(FileName, "")
End Function