Save Word Doc as contents of a certain Cell - vba

I am trying to set the name of my Word document as the contents of whats in the highlighted cell, given by code; ActiveDocument.Tables(1).Cell(1, 2)
I have to do this for 200+ documents and the name will be in the same spot for all the documents.
This macro selects the desired cell and copies it
ActiveDocument.Tables(1).Cell(1, 2).Select
Selection.Copy
And this one saves the word document as a pdf with the clipboard contents as its name.
Sub rename()
Dim strPath As String
Dim strFileName As String
'set pathname accordingly
strPath = "enter path"
'create the Filename with your selection in Document
strFileName = Trim(Selection.Text) & ".pdf"
ActiveDocument.SaveAs FileName:= _
strPath & strFileName _
, FileFormat:=wdFormatXMLDocument, LockComments:=False, Password:="", _
AddToRecentFiles:=True, WritePassword:="", ReadOnlyRecommended:=False, _
EmbedTrueTypeFonts:=False, SaveNativePictureFormat:=False, SaveFormsData _
:=False, SaveAsAOCELetter:=False
End Sub
The issue is that the second Macro does not work when I select the entire cell
Only when I select specific text, like below
Any solutions for this?
Many thanks again

Try replacing this line:
strFileName = Trim(Selection.Text) & ".pdf"
With this...
With ActiveDocument.Tables(1).Cell(1,2).Range
strFileName=ActiveDocument.Range(Start:=.Start, End:=.End-1) & ".pdf"
End With

In MS Word last character in a cell is always a special character with ASCII code 7 which mark the end of cell. You need to remove this character before using. There might be several way of doing it. You may replace this character as follows:
strFileName = Replace(ActiveDocument.Tables(1).Cell(1, 2).Range.Text, Chr(7), "") & ".pdf"
Or, you may exclude it as follows:
charCount = ActiveDocument.Tables(1).Cell(1, 2).Range.Characters.Count
strFileName = Left(ActiveDocument.Tables(1).Cell(1, 2).Range.Text, charCount - 1)

Related

Macro coding, how to automate renaming a document to the above folders name

I want Word VBA macro to rename the document to the folder it lives in.
Sub SaveAsDOCX()
'
OpenDocName = ActiveDocument.FullName
lengthFileName `enter code here`= Len(OpenDocName)
OpenDocName = Left(OpenDocName, lengthFileName - 4)
'
ChangeFileOpenDirectory (ActiveDocument.Path & "\")
ActiveDocument.SaveAs2 FileName:=(OpenDocName & ".docx"),
FileFormat:=wdFormatXMLDocument, LockComments:=False, Password:="",
AddToRecentFiles:=True, WritePassword:="", ReadOnlyRecommended:=False,
EmbedTrueTypeFonts:=False, SaveFormsData:=False,
SaveAsAOCELetter:=False, CompatibilityMode:=0
ActiveWindow.Close
End Sub
Right now the code functions to rename the DOCX as the old file name, but I want to extract from the directory the folders name, and rename the document that. Unfortunately I need this macro to run in a lot of different folders so I need it to stay dynamic, and can't use explicit folder paths.
'That line gets the Full path to the Folder where the document is located.
ThisDocument.path
'That line get the FullPath to the Document place
ThisDocument.FullName
Example one , you can create a new string for the name document
dim docpath as string
Dim docname As String
docname = VBA.Split(VBA.Mid(ActiveDocument.FullName, VBA.InStrRev(ActiveDocument.FullName, "\") + 1), ".")(0)
DocPath = ThisDocument.Path & "\" & docname & ".docx"
Example 2
dim docpath as string
Dim docname As String
docname = Vba.Split(ActiveDocument,".")(0)
DocPath = ThisDocument.Path & "\" & docname & ".docx"
I do not know if is that you want , please , comment below if that helped you , i want to help you!
Actually pretty simple. Used the ActiveDocument to get the path string, split it, ubound to the top, -1 to locate the parent folders name in the array, and then called that resulting string. The ending code looks like:
Dim name, nameSplit, ParentFolderName
OpenDocName = ActiveDocument.FullName
nameSplit = Split(OpenDocName, "\")
ParentFolderName = (UBound(nameSplit) - 1)
and then when performing SaveAs2 call the following as the FileName:=
(nameSplit(ParentFolderName) & ".docx")

save Excel with date in name

I am trying to build a macro that will save my Excel file with the specified name (customer and date).
Not working so far and as I am not very fluent in VBA maybe someone here would be willing to help:
Sub Save()
Sheets("Tool").Unprotect Password:="xxxx"
Dim fclient As String
Dim path As String
fclient = Range("G11").Value
path = Application.ActiveWorkbook.path
fname = "Discount for " & fclient
Application.ActiveWorkbook.SaveAs Filename:=path & "\" & fname & Format(Now, "DD-MM-YYYY"), FileFormat:=52, CreateBackup:=False
Sheets("Tool").Protect Password:="xxxx"
End Sub
Try using ThisWorkbook instead of Activeworkbook
Rather than putting the Format(Now(DD-MM-YYYY)) directly into your path, you can set the date into a cell in the sheet and then use the cells value as part of the file name the same as you have done for the clients name.
The Date function uses your current system date in the DD/MM/YYYY format rather than DD/MM/YYYY HH:MM:SS which Now uses.
I've adapted this to your code along with a 'find and replace' code to find the "/" in the date and replace it with "_". (NOTE this was simply recorded and could be written better I'm sure.) You could change the underscore to any other valid character for a file name if you wish.
In my test I removed Path as if you omit a path in the file name it will use the current files path.
Sub Save()
Dim fclient As String
Dim tdate As String
Range("G12") = Date
tdate = Range("G12")
fclient = Range("G11")
Cells(12, 7).Replace What:="/", Replacement:="_", LookAt:=xlPart, SearchOrder _
:=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False
tdate = Range("G12")
fname = "Discount for " & fclient
ThisWorkbook.SaveAs Filename:="\" & fname & "_" & tdate _
, FileFormat:=xlOpenXMLWorkbookMacroEnabled, CreateBackup:=False
End Sub
I've assumed cell G12 is able to contain the date.
Why your original code doesn't work i'm not sure but this is an alternative.

Excel Workbook to Create Word Document and Auto-Run Mail Merge from Excel Workbook

I've got a bit of a tricky one here. Attempting to simplify an existing process.
Existing Process:
Word Document ("Plan Doc Template") is entirely composed of INCLUDETEXT fields that pull Bookmarked sections from another Word Document ("Source Plan Doc" we'll call it) that includes merge-fields in its bookmarked sections which are from an Excel Workbook ("Mail Merge Workbook").
The current process involves the user copying a Plan Doc Template and a Mail Merge Workbook and pasting it into any folder they choose. The user then fills out the Mail Merge Workbook, saves and closes, and runs a Mail Merge through the Plan Doc Template Word Doc. This pulls in bookmarked sections from the Source Plan Doc depending on the Mail Merge Workbook fields selected. The user then removes all INCLUDETEXT fields with CTRL + SHIFT + F9 to turn fields of Plan Doc Template into workable text.
(Hopeful) Future Process:
The user copies a Mail Merge Workbook and pastes it into their
desired folder. Fills out the Mail Merge Workbook. (Manual Step)
Runs VBA Code.
VBA copies the Plan Doc Template and pastes in the Mail Merge Workbook's folder that just ran the VBA code.
VBA renames the Plan Doc Template Word Doc based on fields within the Mail Merge Workbook.
VBA runs a Mail Merge within the Plan Doc Template
VBA highlights entire document and CTRL + SHIFT + F9 to turn Field Codes into workable text.
Is it possible to do all this from an Excel VBA code or would I need a separate code after the Plan Doc has been created to run the mail merge and do the CTRL + SHIFT + F9 steps?
P.S. I use Excel Worksheets via DDE Selection to get the correct formatting from Mail Merge Workbook to Document. Hoping that can be included in the VBA code, as well.
Help would be greatly appreciated on this one, thanks,
Rich
It looks like you can have the whole thing run with one macro from Excel, without the user having to run a second one, using a For loop until wdApp.Documents.Count increases by 1. I did test the following, but with only a very small data set, so it ran very quickly.
Since the user might have more than just the main merge document open, it's important the code can identify and work with the resulting document. Usually, it will have become the ActiveDocument but relying on that is never certain. So I built in a couple of loops to 1) hold the currently open documents in an array then 2) compare those to the currently active document. If the currently active document is not in the array, then the fields are unlinked (that's the equivalent of Ctrl+Shift+F9).
Of course, if you really wanted to identify the new document from all the documents you'd need to loop each document and loop the array, making the comparison. But I've given you the starting point...
Sub MergeWithWord()
Dim wdApp As Object
Dim wdDoc As Object
Dim nrDocs As Long
Dim i As Long, d As Long
Dim aDocs() As Variant
Set wdApp = GetObject(, "Word.Application")
nrDocs = wdApp.documents.Count
'Get all opened documents so can compare whether a new one
ReDim Preserve aDocs(nrDocs - 1)
Set wdDoc = wdApp.activedocument
For i = 0 To nrDocs - 1
Set aDocs(i) = wdApp.documents(i + 1)
Next
If wdDoc.MailMerge.MainDocumentType <> -1 Then
wdDoc.MailMerge.Destination = 0
wdDoc.MailMerge.Execute False
Do Until wdApp.documents.Count > nrDocs Or i > 1000
i = i + 1
Loop
Set wdDoc = wdApp.activedocument
For d = 0 To UBound(aDocs)
If wdDoc Is aDocs(d) Then
Debug.Print "Not a new doc"
Else
Debug.Print wdDoc.FullName
wdDoc.Fields.Unlink
Exit For
End If
Next
End If
Debug.Print nrDocs, i
MsgBox "Done"
End Sub
May not be the most elegant code but here was what I wound up using to solve my question in case it helps anyone else.
Sub ButtonMerge()
Dim str1 As String
Dim PlanDocTemplate As String
Dim EDrive As String
Dim answer1 As Integer
Dim answer2 As Integer
answer1 = MsgBox("Is this IC Plan Workbook saved in the appropriate Client folder?", vbYesNo + vbQuestion)
If answer1 = vbNo Then
MsgBox ("Please save this IC Plan Workbook in the appropriate Client folder then run again.")
Exit Sub
Else
'do nothing
End If
str1 = "Q:\IC\New Structure\IC Toolkit\Templates\01 Plan Doc Template\16 Source\IC Plan Doc Template v1.0.docx"
PlanDocTemplate = Application.ActiveWorkbook.Path & "\" & Range("A1").Value & ".docx"
EDrive = "E:\" & Range("A1").Value & ".docx"
If Len(Dir(Application.ActiveWorkbook.Path & "\" & Range("A1").Value & ".docx")) = 0 Then
Call FileCopy(str1, PlanDocTemplate)
Else
MsgBox ("The Plan document already exists, please delete or rename the existing Plan Doc in folder " _
& Application.ActiveWorkbook.Path & "\ before creating a new one.")
Exit Sub
End If
strWorkbookName = ThisWorkbook.Path & "\" & ThisWorkbook.Name
Worksheets("Data").Activate
'Opens New Plan Doc Template
Set appWD = CreateObject("Word.Application")
appWD.Visible = True
appWD.Documents.Open Filename:=PlanDocTemplate
ActiveDocument.MailMerge.OpenDataSource Name:=strWorkbookName, _
Format:=wdMergeInfoFromExcelDDE, _
ConfirmConversions:=True, _
ReadOnly:=False, _
LinkToSource:=True, _
AddToRecentFiles:=False, _
PasswordDocument:="", _
PasswordTemplate:="", _
Revert:=False, _
Connection:="Entire Spreadsheet", _
SQLStatement:="SELECT * FROM `Data$`", _
SQLStatement1:="", _
SubType:=wdMergeSubTypeOther
appWD.Visible = True
appWD.Selection.WholeStory
appWD.Selection.Fields.Update
appWD.Selection.Fields.Unlink
ActiveDocument.MailMerge.MainDocumentType = wdNotAMergeDocument
appWD.ActiveDocument.Save
Worksheets("Form").Activate
MsgBox "Successfully Created " & Range("A1").Value & " in Location: " & Application.ActiveWorkbook.Path & "\"
answer2 = MsgBox("Do you want to save a draft in the E:\ drive as well?", vbYesNo + vbQuestion, "E: Drive Copy")
If answer2 = vbYes Then
If Dir("E:\") <> "" Then
ActiveDocument.SaveAs2 Filename:= _
"E:\" & Range("A1").Value & ".docx", _
FileFormat:=wdFormatXMLDocument, LockComments:=False, Password:="", _
AddToRecentFiles:=True, WritePassword:="", ReadOnlyRecommended:=False, _
EmbedTrueTypeFonts:=False, SaveNativePictureFormat:=False, SaveFormsData _
:=False, SaveAsAOCELetter:=False, CompatibilityMode:=14
MsgBox ("Successfully Created " & Range("A1").Value & " in E:\ Location.")
Exit Sub
Else
MsgBox ("Please open the E:\ drive and enter your username/password." & _
vbCrLf & vbCrLf & "Click Ok when E:\ drive is opened.")
If Len(Dir("E:\")) = 0 Then
MsgBox ("Error connecting to E:\ drive." & vbCrLf & vbCrLf & "Please ensure you're connected and try again.")
Exit Sub
Else
ActiveDocument.SaveAs2 Filename:= _
"E:\" & Range("A1").Value & ".docx", _
FileFormat:=wdFormatXMLDocument, LockComments:=False, Password:="", _
AddToRecentFiles:=True, WritePassword:="", ReadOnlyRecommended:=False, _
EmbedTrueTypeFonts:=False, SaveNativePictureFormat:=False, SaveFormsData _
:=False, SaveAsAOCELetter:=False, CompatibilityMode:=14
MsgBox ("Successfully Created " & Range("A1").Value & " in E:\ Location.")
Exit Sub
End If
End If
Else
Exit Sub
End If
End Sub

Use Field Code as File Name in Mail Merge

I want to separate my mail merge into separate PDF files (this part is working). But the file names are being saved as a counter i.e. numbers.
Sub AllSectionsToSubDoc()
Dim x As Long
Dim Sections As Long
Dim Doc As Document
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Set Doc = ActiveDocument
Sections = Doc.Sections.Count
For x = Sections - 1 To 1 Step -1
Doc.Sections(x).Range.Copy
Documents.Add
ActiveDocument.Range.Paste
ActiveDocument.SaveAs (Doc.Path & "\" & x & ".pdf")
ActiveDocument.Close False
Next x
Application.ScreenUpdating = True
Application.DisplayAlerts = True
End Sub
I want to extend this code so that it saves the files with file names which are NOT numbers, but are taken from one of the field codes that I specify.
For example if I specify field code «First_Name» as the file name in my VBA code, and there are 3 names - (John, Peter, Samuel) 3 files should be saved in my destination folder as John.pdf, Peter.pdf, Samuel.pdf
Get the value from the data source, Split between commas, loop through the returned array and save each document individually.
Something like this (I haven't been able to test it).
Dim Value As String
Dim Names As Variant
Dim idx As Long
Value = Doc.DataSource.DataFields("First_Name").Value
Names = Split(Value, ",")
For idx = LBound(Names) To UBound(Names)
ActiveDocument.SaveAs Doc.Path & "\" & Names(idx) & ".pdf"
Next
In the event where the value is a single name (no comma), the Split() function will return an array with a single element.
I managed to find a very simple solution to this. After creating the mail merge, I previewed the results and ran the following macro
ChangeFileOpenDirectory "C:\User\Documents\folder\"
ActiveDocument.ExportAsFixedFormat OutputFileName:= _
" C:\User\Documents\folder\" & ActiveDocument.MailMerge.DataSource.DataFields("Field") & ".pdf", _
ExportFormat:=wdExportFormatPDF, OpenAfterExport:=False, OptimizeFor:= _
wdExportOptimizeForOnScreen, Range:=wdExportAllDocument, From:=1, To:=1, _
Item:=wdExportDocumentContent, IncludeDocProps:=True, KeepIRM:=True, _
CreateBookmarks:=wdExportCreateNoBookmarks, DocStructureTags:=True, _
BitmapMissingFonts:=True, UseISO19005_1:=False
ActiveDocument.MailMerge.DataSource.ActiveRecord = wdNextRecord
and then just loop until the end

Loop through all Word Files in Directory

I have the following code:
Sub WordtoTxtwLB()
'
' WordtoTxtwLB Macro
'
'
Dim fileName As String
myFileName = ActiveDocument.Name
ActiveDocument.SaveAs2 fileName:= _
"\\FILE\" & myFileName & ".txt", FileFormat:= _
wdFormatText, LockComments:=False, Password:="", AddToRecentFiles:=True, _
WritePassword:="", ReadOnlyRecommended:=False, EmbedTrueTypeFonts:=False, _
SaveNativePictureFormat:=False, SaveFormsData:=False, SaveAsAOCELetter:= _
False, Encoding:=1252, InsertLineBreaks:=True, AllowSubstitutions:=False, _
LineEnding:=wdCRLF, CompatibilityMode:=0
End Sub
I want to loop this sub through all of the word (.doc) files in a directory. I have the following code:
Sub LoopDirectory()
vDirectory = "C:\programs2\test"
vFile = Dir(vDirectory & "\" & "*.*")
Do While vFile <> ""
Documents.Open fileName:=vDirectory & "\" & vFile
ActiveDocument.WordtoTxtwLB
vFile = Dir
Loop
End Sub
But it is not working. How do I get this to work either by altering the current code or using new code?
You don't actually need the WordtoTxtwLB Macro. You can combine both the codes. see this example
Sub LoopDirectory()
Dim vDirectory As String
Dim oDoc As Document
vDirectory = "C:\programs2\test\"
vFile = Dir(vDirectory & "*.*")
Do While vFile <> ""
Set oDoc = Documents.Open(fileName:=vDirectory & vFile)
ActiveDocument.SaveAs2 fileName:="\\FILE\" & oDoc.Name & ".txt", _
FileFormat:=wdFormatText, _
LockComments:=False, _
Password:="", _
AddToRecentFiles:=True, _
WritePassword:="", _
ReadOnlyRecommended:=False, _
EmbedTrueTypeFonts:=False, _
SaveNativePictureFormat:=False, _
SaveFormsData:=False, _
SaveAsAOCELetter:=False, _
Encoding:=1252, _
InsertLineBreaks:=True, _
AllowSubstitutions:=False, _
LineEnding:=wdCRLF, _
CompatibilityMode:=0
oDoc.Close SaveChanges:=False
vFile = Dir
Loop
End Sub
BTW, are you sure you want to use the *.* wildcard? What if there are Autocad files in the folder? Also ActiveDocument.Name will give you the file name with the Extension.
To edit all the word documents in a directory I built this simple subroutine.
The subRoutine loops through the directory and
opens each *.doc file it finds. Then on the open document file it calls
the second subRoutine. After the second subRoutine is finished the document
is saved and then closed.
Sub DoVBRoutineNow()
Dim file
Dim path As String
path = "C:\Documents and Settings\userName\My Documents\myWorkFolder\"
file = Dir(path & "*.doc")
Do While file <> ""
Documents.Open FileName:=path & file
Call secondSubRoutine
ActiveDocument.Save
ActiveDocument.Close
file = Dir()
Loop
End Sub
~~~~~~
Here's my solution. I think it's easy to understand and straight forward for newbies like me that I will post my code here. Because I searched around and the codes I saw were kind of complicated. Let's go.
Sub loopDocxs()
Dim wApp As Word.Application
Dim wDoc As Word.Document
Dim mySource As Object
Set obj = CreateObject("Scripting.FileSystemObject")
Set mySource = obj.GetFolder("D:\docxs\")
For Each file In mySource.Files 'loop through the directory
If Len(file.Name) > 0 And InStr(1, file.Name, "$") = 0 Then '$ is temp file mask
Set wApp = CreateObject("Word.Application")
wApp.Visible = True
'Word.Application doesn't recognize file here event if it's a word file.
'fortunately we have the file name which we can use.
Set wDoc = wApp.Documents.Open(mySource & "\" & file.Name, , ReadOnly)
'Do your things here which will be a lot of code
wApp.Quit
Set wApp = Nothing
End If
Next file