Opening and Saving Word Document to new File Location from Excel - excel

I am trying to open a word document from excel and then save as to a new file location using a dialog box.
The problem is it saves the excel file rather than the word file that was opened.
Option Explicit
Sub SaveWordDoc()
Dim WordApp As Object, WordDoc As Object, path As String
Dim dlgSaveAs As FileDialog
' Allows word document to be selected and opened
With Application.FileDialog(msoFileDialogOpen)
.Show
If .SelectedItems.Count = 1 Then
path = .SelectedItems(1)
End If
End With
If path = "" Then
Exit Sub
End If
Set WordApp = CreateObject("Word.Application")
Set WordDoc = WordApp.Documents.Open(path)
WordApp.Visible = False
'Opens Save As dialog box
Set dlgSaveAs = Application.FileDialog( _
FileDialogType:=msoFileDialogSaveAs)
dlgSaveAs.Show
WordApp.ActiveDocument.Close
WordApp.Quit
Set WordApp = Nothing
Set WordDoc = Nothing
End Sub

Thank you BigBen your suggestion works well as long as the a word document format is selected.
Option Explicit
Sub Test()
Dim WordApp As Object, WordDoc As Object, path As String
Dim dlgSaveAs As FileDialog, fileSaveName As Variant
' To get the code to function I had to include the Microsoft Word 16 Object
'Library.
'From the excel VBA editor window. Tools > References then ensure Microsoft Word
'16.0 Object Library is checked.
' Allows word document to be selected and opened
With Application.FileDialog(msoFileDialogOpen)
.Show
If .SelectedItems.Count = 1 Then
path = .SelectedItems(1)
End If
End With
If path = "" Then
Exit Sub
End If
Set WordApp = CreateObject("Word.Application")
Set WordDoc = WordApp.Documents.Open(path)
WordApp.Visible = False
' Allows word document to be saved under a different file location and name
fileSaveName = Application.GetSaveAsFilename( _
fileFilter:="Word Documents (*.docx), *.docx")
WordApp.ActiveDocument.SaveAs2 Filename:=fileSaveName, _
FileFormat:=wdFormatDocumentDefault
WordApp.ActiveDocument.Close
WordApp.Quit
Set WordApp = Nothing
Set WordDoc = Nothing
End Sub

Related

How to convert pdf to xlsx using Excel VBA

I am trying to convert a pdf file to an excel file (xlsx) using excel VBA.
The problem is the code seems to be perfectly fine as I have seen it working on other computers in action, but for some reason, I am getting a run time error and I am trying to solve this for a week.
Below is the code
Option Explicit
Function ClearCipboard()
'Early binding will requires a Reference to 'Microsoft Forms 2.0 Object Library'
Dim oData As Object 'New MSForms.DataObject
Set oData = CreateObject("New:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")
oData.SetText Text:=Empty
oData.PutInClipboard
Set oData = Nothing
End Function
Sub Automate()
Dim PathforPDFfiles As String
Dim PathforExcelfiles As String
PathforPDFfiles = "C:\Users\kvenkat2\Desktop\Trails 18.06.2021\Test File Excel\PDF-to-Excel-Converter\"
PathforExcelfiles = "C:\Users\kvenkat2\Desktop\Trails 18.06.2021\Test File Excel\PDF-to-Excel-Converter\"
Dim fso As New FileSystemObject
Dim myFolder As Folder
Dim myFile As File
Set myFolder = fso.GetFolder(PathforPDFfiles)
Dim WordApp As Object
Dim WordDoc As Object
Dim WordRange As Object
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Set WordApp = CreateObject("word.application")
'Set WordDoc = WordApp.documents.Add
'Set WordApp = New Word.Application
WordApp.Visible = True
Dim nwb As Workbook
Dim nsh As Worksheet
For Each myFile In myFolder.Files
Set WordDoc = WordApp.documents.Open(myFile.Path, False, Format:="PDF Files")
Set WordRange = WordDoc.Paragraphs(1).Range
WordRange.WholeStory
Set nwb = Workbooks.Add
Set nsh = nwb.Sheets(1)
WordRange.Copy
nsh.Paste
nwb.SaveAs (PathforExcelfiles & Replace(myFile.Name, ".pdf", ".xlsx"))
Application.CutCopyMode = False
Call ClearCipboard
WordDoc.Close True
nwb.Close True
Next
WordApp.Quit
Set WordDoc = Nothing
Set WordApp = Nothing
Application.displayAlters = True
Application.ScreenUpdating = False
MsgBox ("Done for real")
End Sub
Set WordDoc = WordApp.documents.Open(myFile.Path, False, Format:="PDF Files")
This is the part where my code stops running and I try to see the opened word and nothing happens from here. I am unable to get past this line.
It shows as a run time error as shown in the image

How to use "selection" in word to move the cursor with VBA code in excel?

I have a "Userform" in excel which has a button.
When the button is clicked, VBA will open a Word document and find a string in Word table.
When finding the string, the cursor should move to the next row, but it doesn't work.
Here are my documents.
https://drive.google.com/file/d/1dhGoWxdaBxL2WmqsfFT6wllJ5z1d9csH/view?usp=sharing
Private Sub CommandButton2_Click()
Dim path As String
path = ThisWorkbook.path & "\範本.docx"
'Debug.Print (path)
Set WordApp = CreateObject("Word.Application")
WordApp.Documents.Open (path)
WordApp.Visible = True
WordApp.Activate
WordApp.Selection.homekey unit:=6
WordApp.Selection.Find.Execute FindText:="編號" ', Forward:=True, Wrap:=wdFindStop
WordApp.Selection.MoveRight = 2
WordApp.Selection.InsertAfter = LB_Num.Caption
End Sub
I found this way can work.
Private Sub CommandButton1_Click()
Dim str As String
str = TextBox1.Text
Dim WordApp As Word.Application
Set WordApp = New Word.Application
WordApp.Documents.Open ThisWorkbook.Path & "\test.docm"
WordApp.Visible = True
WordApp.Selection.Find.Execute FindText:="編號"
WordApp.Selection.Move Unit:=wdCell, Count:=1
WordApp.Selection.InsertAfter str
WordApp.Documents.Save
Set WordApp = Nothing
End Sub
And need add Microsoft word Library first!

Strange behavior on running Powerpoint VBA updating Excel links

I need some help with some bizzare VBA code behavior in Powerpoint. Purpose is simple - update Excel links on a Powerpoint presentation. I have a presentation with objects linked to an Excel file. On running the code from Powerpoint, a user is prompted to select the source Excel file on the harddrive, and the location of this Excel file is used to replace the previous location of the Excel file, already saved in the PowerPoint presentation.
You run the macro, check the links, their path is updated. You click save, close the presentation. You open the presentation and all is good.
Now let’s say you change the name of the Excel file. You run the macro, check the links, their path is updated. You click save, close the presentation. You open the presentation and ONLY HALF THE LINKS ARE UPDATED. Could somebody take a look? Thanks!
Private Sub CommandButton1_Click()
Dim xlApp As Object
Dim xlWorkBook As Object
Dim pptSlide As Slide
Dim pptShape As Shape
Dim oldString, tempString, newString As String
Dim intLength As Integer
Dim sPath As String
Dim ExcelFileName As String
Dim fd As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
With fd
.AllowMultiSelect = False
' Set the title of the dialog box.
.Title = "Please select the file to update links in the presentation"
' Clear out the current filters, and add our own.
.Filters.Clear
.Filters.Add "Excel Workbook", "*.xlsx"
' Show the dialog box. If the .Show method returns True, the
' user picked at least one file. If the .Show method returns
' False, the user clicked Cancel.
If .Show = True Then
newString = .SelectedItems(1) 'replace txtFileName with your textbox
End If
End With
'show "macro running" screen
UserForm1.Show False
'open excel file with links
Set xlApp = CreateObject("Excel.Application")
Set xlWorkBook = xlApp.Workbooks.Open(newString, True, False)
'grab old full path to replace link in objects
For Each pptSlide In ActivePresentation.Slides
For Each pptShape In pptSlide.Shapes
If pptShape.Type = msoLinkedOLEObject Then
tempString = pptShape.LinkFormat.SourceFullName
intLength = InStr(tempString, "!")
oldString = Mid(tempString, 1, intLength - 1)
GoTo 1
End If
If pptShape.Type = msoChart Then
oldString = pptShape.LinkFormat.SourceFullName
GoTo 1
End If
Next pptShape
Next pptSlide
1
'replace old full path to new full path
For Each pptSlide In ActivePresentation.Slides
For Each pptShape In pptSlide.Shapes
If pptShape.Type = msoLinkedOLEObject Or pptShape.Type = msoChart Then
With pptShape.LinkFormat
If InStr(1, UCase(.SourceFullName), UCase(oldString)) Then
.SourceFullName = Replace(.SourceFullName, oldString, newString)
End If
End With
pptShape.LinkFormat.Update
End If
'DoEvents
Next pptShape
'DoEvents
Next pptSlide
'close excel file with links
xlWorkBook.Close (False)
xlApp.Quit
Set xlApp = Nothing
Set xlWorkBook = Nothing
'hide "macro running" screen
UserForm1.Hide
End Sub

Excel VBA to Open Multiple Word 2010 Documents and Determine if Checkboxes are Checked

I'm trying to create a report that analyzes multiple word documents in a folder and analyzes checkboxes in the document to determine if a set of tests passed or failed. I have code that loops through all documents in a folder, but I'm having a hard time determining how to determine if the boxes are checked.
The first checkbox I'm trying to evaluate is tagged "PassCheckBox". I've found several articles with syntax on how to do this, but none seem to work with the way I'm iterating through the word files. My current code give me "Object is Required" when I try to run.
Here is my current code:
Sub ParseTestFiles()
Dim FSO As Object
Dim fPath As String
Dim myFolder, myFile
Dim wdApp As Object
Dim PassValue As Boolean
fPath = ActiveWorkbook.Path
Set FSO = CreateObject("Scripting.FileSystemObject")
Set myFolder = FSO.GetFolder(fPath).Files
For Each myFile In myFolder
If LCase(myFile) Like "*.doc" _
Or LCase(myFile) Like "*.docx" Or LCase(myFile) Like "*.docm" Then
On Error Resume Next
Set wdApp = GetObject(, "Word.Application")
If Err.Number <> 0 Then 'Word not yet running
Set wdApp = CreateObject("Word.Application")
End If
On Error GoTo 0
wdApp.Documents.Open CStr(myFile)
wdApp.Visible = True
' Here is where I'm having an issue
PassValue = ActiveDocument.FormFields("PassCheckBox").Checked
Set wdApp = Nothing
End If 'LCase
Next myFile
End Sub
Try to use:
Dim c, wdDoc
Set wdDoc = wdApp.Documents.Open(CStr(myFile))
wdApp.Visible = True
For Each c In wdDoc.ContentControls
If c.Title = "PassCheckBox" Then
PassValue = c.Checked
Exit For
End If
Next
instead
wdApp.Documents.Open CStr(myFile)
wdApp.Visible = True
PassValue = ActiveDocument.FormFields("PassCheckBox").Checked

Copy entire worksheet contents into already open Word document

I have two partial working bits of code to put together.
I have a worksheet labeled 'word' that I want to export and save automatically under a variable.
Sub CreateNewWordDoc()
Dim wrdApp As Word.Application
Dim wrdDoc As Word.Document
Dim i As Integer
docname = Worksheets("input").Range("b10").Value
Data1 = Worksheets("word").Range("a1:d103").Value
Set wrdApp = CreateObject("Word.Application")
wrdApp.Visible = True
Set wrdDoc = wrdApp.Documents.Open("C:\Results\ResultsTemplate.doc")
'******THIS IS TO EDIT THE WORD DOCUMENT******
With Worksheets("word")
CopyRangeToWord wdDoc, .Range("A1:d104")
'******THIS IS THE END TO EDIT THE WORD DOCUMENT*****
If Dir("C:\Results\" & docname & ".doc") <> "" Then
Kill "C:\Results\" & docname & ".doc"
End If
.SaveAs ("C:\Results\" & docname & ".doc")
.Close ' close the document
End With
wrdApp.Quit ' close the Word application
Set wrdDoc = Nothing
Set wrdApp = Nothing
End Sub
I like this first one the best. It will open my template that has all the official stuff that these generated reports will require (company info etc) and will automatically save and close with the correct file name. However, I cannot find a way to get it to copy all the information from the worksheet 'word' into the text body of the document. It is saving a blank document.
While troubleshooting, I came across this code:
Private Sub CopyRangeToWord(ByRef wdDoc As Word.Document, rng_to_copy As Range, Optional page_break As Boolean = True)
' Will copy the range given into the word document given.
Application.StatusBar = "Copying data from " & rng_to_copy.Parent.Name & "..."
rng_to_copy.Copy
wdDoc.Paragraphs(wdDoc.Paragraphs.Count).Range.InsertParagraphAfter
wdDoc.Paragraphs(wdDoc.Paragraphs.Count).Range.Paste
Application.CutCopyMode = False
wdDoc.Paragraphs(wdDoc.Paragraphs.Count).Range.InsertParagraphAfter
' insert page break after all worksheets except the last one
If page_break Then
With wdDoc.Paragraphs(wdDoc.Paragraphs.Count).Range
.InsertParagraphBefore
.Collapse Direction:=wdCollapseEnd
.InsertBreak Type:=wdPageBreak
End With
End If
End Sub
Sub CopyWorksheetsToWord()
Dim wdApp As Word.Application, wdDoc As Word.Document, ws As Worksheet
Application.ScreenUpdating = False
Application.StatusBar = "Creating new document..."
Set wdApp = New Word.Application
Set wdDoc = wdApp.Documents.Add
docname = Worksheets("input").Range("b10").Value
With Worksheets("word")
CopyRangeToWord wdDoc, .Range("A1:d104")
End With
Set ws = Nothing
Application.StatusBar = "Cleaning up..."
'apply normal view
With wdApp.ActiveWindow
If .View.SplitSpecial = wdPaneNone Then
.ActivePane.View.Type = wdNormalView
Else
.View.Type = wdNormalView
End If
End With
Set wdDoc = Nothing
wdApp.Visible = True
Set wdApp = Nothing
Application.StatusBar = False
End Sub
which does the exact opposite of the first code: it will open up a new document (not the template), will copy all the data perfectly but will not save or close with correct filenames.
I am guessing that it will be easier to update code section one to copy the worksheet contents, and is what I would prefer.
Private Sub CopyRangeToWord(ByRef wdDoc As Word.Document, rng_to_copy As Range, Optional page_break As Boolean = True)
' Will copy the range given into the word document given.
Application.StatusBar = "Copying data from " & rng_to_copy.Parent.Name & "..."
rng_to_copy.Copy
wdDoc.Paragraphs(wdDoc.Paragraphs.Count).Range.InsertParagraphAfter
wdDoc.Paragraphs(wdDoc.Paragraphs.Count).Range.Paste
Application.CutCopyMode = False
wdDoc.Paragraphs(wdDoc.Paragraphs.Count).Range.InsertParagraphAfter
' insert page break after all worksheets except the last one
If page_break Then
With wdDoc.Paragraphs(wdDoc.Paragraphs.Count).Range
.InsertParagraphBefore
.Collapse Direction:=wdCollapseEnd
.InsertBreak Type:=wdPageBreak
End With
End If
End Sub
Sub CopyWorksheetsToWord()
Dim wdApp As Word.Application, wdDoc As Word.Document, ws As Worksheet
Application.ScreenUpdating = False
Application.StatusBar = "Creating new document..."
Set wdApp = New Word.Application
Set wdDoc = wdApp.Documents.Add
docname = Worksheets("input").Range("b10").Value
With Worksheets("word")
CopyRangeToWord wdDoc, .Range("A1:d104")
With wdDoc
.SaveAs ("C:\Results\" & docname & ".doc")
.Close
End With
End With
End Sub
this works: but does not open from my template. nonetheless - it will create a document from one worksheet and automatically save it to the directory with the filename referenced in a defined cell.

Resources