Macros

D

Doug

If this is the wrong forum, please help on re-direct.

I need to create a macro to save a file to a specific
location, but with a file name based on the first 2 words
in the document. (different name each time) Any takers?
 
D

dsc

One option would be to select the first two words, then run a macro that uses the Selection property to get those selected words in a string variable, add any other chars you want to the string, then SaveAs.

Sub SaveAsFirstTwoWords()
Dim NameString As String
Dim PathString As String
If Selection.Type = wdSelectionNormal Then
PathString = "C:\wherever\wherever\wherever"
NameString = PathString & Selection & "WhateverElse"
ActiveDocument.SaveAs FileName:=NameString
Else
MsgBox "Nothing is Selected"
End
End If
End Sub

You could put that macro in a drop-down menu, a toolbar button, or a hotkey. Select the first two words of the file, then run it.
 
D

dsc

Oh, and to avoid overwriting existing files, you might want to add something
like this:

Dim fs
Set fs = CreateObject("Scripting.FileSystemObject")

If fs.FileExists(NameString) Then
ActiveDocument.SaveAs FileName:=NameString
Else
MsgBox "Honk off, Bozo. " & NameString & " already exists."
End
End If
 
D

dsc

Well, that'll larn me to post when I'm groggy with fattygue.

I gooned up the check for the file. Try it this way:

Sub SaveAsFirstTwoWords()
Dim NameString As String
Dim PathString As String
Dim fs

Set fs = CreateObject("Scripting.FileSystemObject")

If Selection.Type = wdSelectionNormal Then
PathString = "C:\" 'wherever\wherever\wherever"
NameString = PathString & Selection & ".doc"
If Not fs.FileExists(NameString) Then
ActiveDocument.SaveAs FileName:=NameString
Else
MsgBox "Honk off, Bozo. " & NameString & " already exists."
End
End If
Else
MsgBox "Nothing is Selected"
End
End If
End Sub
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top