.Find not working in Word from Excel vba - vba

I'm trying to get information from a table in Word and pull it into Excel, since the number of tables is variable and I have no other way to reference the table I wanted to find the table directly after the text before it in the document. I've used the .Find method before but for some reason I can't get it to work this time and from everything I've read and used before, this should work:
Sub Process_NIM()
Dim WordPullFile As Object
Dim PullFolder As String
Dim PullDate As Date
Dim AppWord As Word.Application
Dim wd As Word.Document
Dim Table1 As Word.Table
Dim wb As Workbook
Dim ws1, ws2 As Worksheet
Dim Text1 As Word.Range
PullDate = DateAdd("d", 1, Now())
PullFolder = "M:\Production Case Files\" & Format(PullDate, "YYYY") & _
" Production Case Files\" & UCase(Format(PullDate, "MMM")) & _
"\" & UCase(Format(PullDate, "MMM DD")) & "\"
On Error GoTo OpenFileError
Set WordPullFile = Application.FileDialog(msoFileDialogOpen)
With WordPullFile
.AllowMultiSelect = False
.Filters.clear
.Filters.Add "DOC Files (*.doc)", "*.doc"
.InitialFileName = PullFolder
.Show
End With
On Error GoTo 0
If WordPullFile.SelectedItems.Count > 0 Then
PullFolder = WordPullFile.SelectedItems(1)
End If
Set AppWord = CreateObject("Word.Application")
Set wd = AppWord.Documents.Open(PullFolder)
wd.Application.Visible = True
Set wb = ThisWorkbook
Set ws1 = wb.Worksheets(1)
Set ws2 = wb.Worksheets(2)
If Text1.wd.Selection.Find.Execute(findtext:="Generator Outages for Today - Greater than 25MW") = True Then
'do stuff
End If
OpenFileError:
MsgBox ("There was an error opening the word file. Try closing any other instances of word and re-run.")
Exit Sub
End Sub
I use this from Word currently, but I can't get it to work from Excel:
If Text1.Find.Execute(findtext:="RC South Regional Review for") Then
Text1.InsertAfter (" " & Format(FileDate, "MMMM DD, YYYY"))
End If

the good news is, the text you say you use in word that doesn't work in excel, actually does work. The issue is with the value you are trying to put in, I used your code and for a while I was stumped because it appeared to not be working, but when I substituted some plain text instead of your date, it worked fine, whihc told me the find was working. It turns out it simply wasn't resolving Filedate as a date and so wasn't inserting anything. Here is a version of your code, modified to work on my PC that does insert a date after the found string, did you mean to add Pulldate instead of Filedate as the variable to append maybe?
Sub Process_NIM()
Dim WordPullFile As Object
Dim PullFolder As String
Dim PullDate As Date
Dim AppWord As Word.Application
Dim wd As Word.Document
Dim Table1 As Word.Table
Dim wb As Workbook
Dim ws1, ws2 As Worksheet
Dim Text1 As Word.Range
PullDate = DateAdd("d", 1, Now())
PullFolder = "D:\Users\Mark\Documents\"
On Error GoTo OpenFileError
Set WordPullFile = Application.FileDialog(msoFileDialogOpen)
With WordPullFile
.AllowMultiSelect = False
.Filters.Clear
.Filters.Add "DOC Files (*.doc)", "*.doc"
.InitialFileName = PullFolder
.Show
End With
On Error GoTo 0
If WordPullFile.SelectedItems.Count > 0 Then
PullFolder = WordPullFile.SelectedItems(1)
End If
Set AppWord = CreateObject("Word.Application")
Set wd = AppWord.Documents.Open(PullFolder)
wd.Application.Visible = True
Set wb = ThisWorkbook
Set ws1 = wb.Worksheets(1)
Set ws2 = wb.Worksheets(2)
Set Text1 = wd.Range
If Text1.Find.Execute(findtext:="RC South Regional Review for") Then
Text1.InsertAfter (" " & Format(Date, "MMMM DD, YYYY"))
Else
MsgBox "could not find text"
End If
wd.Save
wd.Close
AppWord.Quit
Set AppWord = Nothing
Exit Sub
OpenFileError:
MsgBox ("There was an error opening the word file. Try closing any other instances of word and re-run.")
Exit Sub
End Sub

Related

OLE and/or runtime 438 errors when pulling Word Form data into Excel workbook

This script worked perfectly... until it didn't. I have an Excel workbook in the same folder as multiple copies of a Word form. The macro should pull the data from each form and copy it to a row in the workbook. I now get either "OLE Excel is waiting on another application" errors or Runtime 438 errors. The macro I use is as follows:
Sub GetFormData()
Application.ScreenUpdating = False
Dim wdApp As New Word.Application
Dim wdDoc As Word.Document
Dim CCtrl As Word.ContentControl
Dim strFolder As String, strFile As String
Dim WkSht As Worksheet, i As Long, j As Long
strFolder = GetFolder
If strFolder = "" Then Exit Sub
Set WkSht = ActiveSheet
i = WkSht.Cells(WkSht.Rows.Count, 1).End(xlUp).Row
strFile = Dir(strFolder & "\*.docm", vbNormal)
While strFile <> ""
i = i + 1
Set wdDoc = wdApp.Documents.Open(Filename:=strFolder & "\" & strFile, AddToRecentFiles:=False, Visible:=False)
With wdDoc
j = 0
For Each CCtrl In .ContentControls
j = j + 1
WkSht.Cells(i, j).FormulaLocal = CCtrl.Range.Text
Next
End With
wdDoc.Close SaveChanges:=False
strFile = Dir()
Wend
wdApp.Quit
Set wdDoc = Nothing: Set wdApp = Nothing: Set WkSht = Nothing
Application.ScreenUpdating = True
End Sub
Function GetFolder() As String
Dim oFolder As Object
GetFolder = ""
Set oFolder = CreateObject("Shell.Application").BrowseForFolder(0, "Choose a folder", 0)
If (Not oFolder Is Nothing) Then GetFolder = oFolder.Items.Item.Path
Set oFolder = Nothing
End Function
The issue appears to start at "Set wdDoc = wdApp..."
I am a bit of a noob at this. As such, I appreciate your help.
Matt.
I see two possible issues, the first one is almost certainly causing the error; the second could cause this error (but probably not with VBA):
You declare and instantiate the Word application in the same line:
Dim wdApp As New Word.Application
You shouldn't do this. Instead:
Dim wdApp As Word.Application
Set wdApp = New Word.Application
I don't remember the exact details about the "why", but it's something to do with the Word.Application object being created immediately, and at a level where you can no longer control it using Set wdApp = Nothing.
Correctly, all objects of the "outside" application should be released, in reverse order of their creation. You've declared an object of the type Word.ContentControl, but don't release it:
Set Set CCtrl = Nothing : Set wdDoc = Nothing: Set wdApp = Nothing: Set WkSht = Nothing

Method 'ThisWorkbook' of object '_Global' failed - Exporting comments from Word to Excel

I am trying to export comments and corresponding text from Word to Excel using this code. I copied and pasted the code into VBA as such:
Option Explicit
Public Sub FindWordComments()
'Requires reference to Microsoft Word v14.0 Object Library
Dim myWord As Word.Application
Dim myDoc As Word.Document
Dim thisComment As Word.Comment
Dim fDialog As Office.FileDialog
Dim varFile As Variant
Dim destSheet As Worksheet
Dim rowToUse As Integer
Dim colToUse As Long
Set fDialog = Application.FileDialog(msoFileDialogFilePicker)
Set destSheet = ThisWorkbook.Sheets("Sheet1")
colToUse = 1
With fDialog
.AllowMultiSelect = True
.Title = "Import Files"
.Filters.Clear
.Filters.Add "Word Documents", "*.docx"
.Filters.Add "Word Macro Documents", "*.docm"
.Filters.Add "All Files", "*.*"
End With
If fDialog.Show Then
For Each varFile In fDialog.SelectedItems
rowToUse = 2
Set myWord = New Word.Application
Set myDoc = myWord.Documents.Open(varFile)
For Each thisComment In myDoc.Comments
With thisComment
destSheet.Cells(rowToUse, colToUse).Value = .Range.Text
destSheet.Cells(rowToUse, colToUse + 1).Value = .Scope.Text
destSheet.Columns(2).AutoFit
End With
rowToUse = rowToUse + 1
Next thisComment
destSheet.Cells(1, colToUse).Value = Left(myDoc.Name, 4)
'Put name of interview object in cell A1
destSheet.Cells(1, colToUse + 1).Value = ActiveDocument.Words.Count
'Put the number of words in cell B1
Set myDoc = Nothing
myWord.Quit
colToUse = colToUse + 2
Next varFile
End If
End Sub
Public Sub PrintFirstColumnOnActiveSheetToSheetName()
ActiveSheet.Name = ActiveSheet.Range("A1")
End Sub
and VBA returns with the error from the title of my post, and highlighting the code:
Set destSheet = ThisWorkbook.Sheets("Sheet1")
Not sure where to go from here, might I add I am an extremely novice coder/VBA user. I just learned now how to create a macro.
Because you are running code from within Word, you first need to initialize an instance of Excel and then reference to the workbook of choice
So insert the following code in the head of your sub and replace "WorkbookName" with the name of your Workbook. Then replace ThisWorkbook in your code with wb
Dim objExcelApp As Object
Dim wb As Object
Set objExcelApp = CreateObject("Excel.Application")
Set wb = objExcelApp.Workbooks("WorkbookName")
If the Workbook is closed replace last line with
Set wb = objExcelApp.Workbooks.Open("C:/Folder1/Book1.xlsm")

Excel VBA to get Word Document Form Data returning incorrect date format

I copied this code to get data from a word document form and put it into an excel spreadsheet and it works great except that the dates are coming in mm/dd/yyyy format. I need to it be dd/mm/yyyy format.
I tried adding a date picker to the form but that hasn't helped.
Normally I would put the formatting into the VBA code but I am unsure how to do that in this code. Can it be inserted or can I somehow reformat the date after it comes into the spreadsheet?
The code is in Excel VBA
Sub GetFormData()
'Note: this code requires a reference to the Word object model
Application.ScreenUpdating = False
Dim wdApp As New Word.Application
Dim wdDoc As Word.Document
Dim CCtrl As Word.ContentControl
Dim strFolder As String, strFile As String
Dim WkSht As Worksheet, i As Long, j As Long
strFolder = GetFolder
If strFolder = "" Then Exit Sub
Set WkSht = Sheets("Data")
i = WkSht.Cells(WkSht.Rows.Count, 1).End(xlUp).Row
strFile = Dir(strFolder & "\*.docx", vbNormal)
While strFile <> ""
i = i + 1
Set wdDoc = wdApp.Documents.Open(Filename:=strFolder & "\" & strFile, AddToRecentFiles:=False, Visible:=False)
With wdDoc
j = 0
For Each CCtrl In .ContentControls
j = j + 1
WkSht.Cells(i, j) = CCtrl.Range.Text
Next
End With
wdDoc.Close SaveChanges:=False
strFile = Dir()
Wend
wdApp.Quit
Set wdDoc = Nothing: Set wdApp = Nothing: Set WkSht = Nothing
Application.ScreenUpdating = True
You may want to replace
WkSht.Cells(i, j) = CCtrl.Range.Text
by
WkSht.Cells(i, j).FormulaLocal = CCtrl.Range.Text

HOW To manipulate an ALREADY open word document from excel vba

I am new to VBA and obviously I am missing something. My code works for opening a word doc and sending data to it BUT does NOT for an ALREADY OPEN word doc. I keep searching for an answer on how to send info from Excel to an OPEN Word doc/Bookmark and nothing works.
I hope it is okay that I added all the code and the functions called. I really appreciate your help!
What I have so far
Sub ExcelNamesToWordBookmarks()
On Error GoTo ErrorHandler
Dim wrdApp As Object 'Word.Application
Dim wrdDoc As Object 'Word.Document
Dim xlName As Excel.Name
Dim ws As Worksheet
Dim str As String 'cell/name value
Dim cell As Range
Dim celldata As Variant 'added to use in the test
Dim theformat As Variant 'added
Dim BMRange As Object
Dim strPath As String
Dim strFile As String
Dim strPathFile As String
Set wb = ActiveWorkbook
strPath = wb.Path
If strPath = "" Then
MsgBox "Please save your Excel Spreadsheet & try again."
GoTo ErrorExit
End If
'GET FILE & path of Word Doc/Dot
strPathFile = strOpenFilePath 'call a function in MOD1
If strPathFile = "" Then
MsgBox "Please choose a Word Document (DOC*) or Template (DOT*) & try again." 'strPath = Application.TemplatesPath
GoTo ErrorExit
End If
If FileLocked(strPathFile) Then 'Err.Number = 70 if open
'read / write file in use 'do something
'NONE OF THESE WORK
Set wrdApp = GetObject(strPathFile, "Word.Application")
'Set wrdApp = Word.Documents("This is a test doc 2.docx")
'Set wrdApp = GetObject(strPathFile).Application
Else
'all ok 'Create a new Word Session
Set wrdApp = CreateObject("Word.Application")
wrdApp.Visible = True
wrdApp.Activate 'bring word visiable so erros do not get hidden.
'Open document in word
Set wrdDoc = wrdApp.Documents.Open(Filename:=strPathFile) 'Open vs wrdApp.Documents.Add(strPathFile)<=>create new Document1 doc
End If
'Loop through names in the activeworkbook
For Each xlName In wb.Names
If Range(xlName).Cells.Count = 1 Then
celldata = Range(xlName.Value)
'do nothing
Else
For Each cell In Range(xlName)
If str = "" Then
str = cell.Value
Else
str = str & vbCrLf & cell.Value
End If
Next cell
'MsgBox str
celldata = str
End If
'Get format and strip away the spacing, negative color etc etc
'I know this is not right... it works but not best
theformat = Application.Range(xlName).DisplayFormat.NumberFormat
If Len(theformat) > 8 Then
theformat = Left(theformat, 5) 'was 8 but dont need cents
Else
'do nothing for now
End If
If wrdDoc.Bookmarks.Exists(xlName.Name) Then
'Copy the Bookmark's Range.
Set BMRange = wrdDoc.Bookmarks(xlName.Name).Range.Duplicate
BMRange.Text = Format(celldata, theformat)
'Re-insert the bookmark
wrdDoc.Bookmarks.Add xlName.Name, BMRange
End If
Next xlName
'Activate word and display document
With wrdApp
.Selection.Goto What:=1, Which:=2, Name:=1 'PageNumber
.Visible = True
.ActiveWindow.WindowState = wdWindowStateMaximize 'WAS 0 is this needed???
.Activate
End With
GoTo WeAreDone
'Release the Word object to save memory and exit macro
ErrorExit:
MsgBox "Thank you! Bye."
Set wrdDoc = Nothing
Set wrdApp = Nothing
Exit Sub
'Error Handling routine
ErrorHandler:
If Err Then
MsgBox "Error No: " & Err.Number & "; There is a problem"
If Not wrdApp Is Nothing Then
wrdApp.Quit False
End If
Resume ErrorExit
End If
WeAreDone:
Set wrdDoc = Nothing
Set wrdApp = Nothing
End Sub
file picking:
Function strOpenFilePath() As String
Dim intChoice As Integer
Dim iFileSelect As FileDialog 'B
Set iFileSelect = Application.FileDialog(msoFileDialogOpen)
With iFileSelect
.AllowMultiSelect = False 'only allow the user to select one file
.Title = "Please... Select MS-WORD Doc*/Dot* Files"
.Filters.Clear
.Filters.Add "MS-WORD Doc*/Dot* Files", "*.do*"
.InitialView = msoFileDialogViewDetails
End With
'make the file dialog visible to the user
intChoice = Application.FileDialog(msoFileDialogOpen).Show
'determine what choice the user made
If intChoice <> 0 Then
'get the file path selected by the user
strOpenFilePath = Application.FileDialog( _
msoFileDialogOpen).SelectedItems(1)
Else
'nothing yet
End If
End Function
checking if file is open...
Function FileLocked(strFileName As String) As Boolean
On Error Resume Next
' If the file is already opened by another process,
' and the specified type of access is not allowed,
' the Open operation fails and an error occurs.
Open strFileName For Binary Access Read Write Lock Read Write As #1
Close #1
' If an error occurs, the document is currently open.
If Err.Number <> 0 Then
' Display the error number and description.
MsgBox "Function FileLocked Error #" & str(Err.Number) & " - " & Err.Description
FileLocked = True
Err.Clear
End If
End Function
ANSWER BELOW. Backstory... So, after input from you guys and more research I discovered that I needed to set the active word document by using the file selection the user picked and that is then passed via late binding to the sub as an object to process. NOW it works if the word file is not in word OR if it is currently loaded into word AND not even the active document. The below code replaces the code in my original question.
Set Object app as word.
grab the file name.
Make the word doc selected active to manipulate.
Set the word object to the active doc.
THANK YOU EVERYONE!
If FileLocked(strPathFile) Then 'Err.Number = 70 if open
'read / write file in use 'do something
Set wrdApp = GetObject(, "Word.Application")
strPathFile = Right(strPathFile, Len(strPathFile) - InStrRev(strPathFile, "\"))
wrdApp.Documents(strPathFile).Activate ' need to set picked doc as active
Set wrdDoc = wrdApp.ActiveDocument ' works!
This should get you the object you need.
Dim WRDFile As Word.Application
Set WRDFile = GetObject(strPathFile)
'Have Microsoft Word 16.0 Object Library selected in your references
Dim wordapp As Object
Set wordapp = GetObject(, "Word.Application")
wordapp.Documents("documentname").Select
'works if you only have one open word document. In my case, I'm trying to push updates to word links from excel.

Search word doc for text and paste into excel file

I'm pretty sure I'm real close on this one, I used a combination of this question for text selection and this other question regarding importing tables for what I've gotten so far.
I'm trying to find certain value in a word file, with the most identifiable preceding text being a "VALUE DATE" on the line above it. The value I want is in the line below this "VALUE DATE". I want the macro to be able to search the word doc for the desired text and paste it into excel, as normally we would have to do this manually about 50 times. Very tedious.
For reference here's what the text looks like in the word doc.
TRANSACTIONS VALUE DATE
31-08-15 X,XXX.XX
I want to pull value X,XXX.XX and paste it into a destination in excel, let's just use A1 for simplicity.
Sub wordscraper9000()
Dim oWordApp As Object, oWordDoc As Object
Dim FlName As String
'''''dim tbl as object --> make string
Dim TextToFind As String, TheContent As String
Dim rng1 As Word.Range
FlName = Application.InputBox("Enter filepath of .doc with desired information")
'establish word app object
On Error Resume Next
Set oWordApp = GetObject(, "Word.application")
If Err.Number <> 0 Then
Set oWordApp = CreateObject("Word.application")
End If
Err.Clear
On Error GoTo 0
oWordApp.Visible = True
'open word doc
Set oWordDoc = oWordApp.documents.Open(FlName)
'--> enter something that will skip if file already open
'''''set tbl = oworddoc.tables(1) --> set word string
'declare excel objects
Dim wb As Workbook, ws As Worksheet
'Adding New Workbook
Set wb = Workbooks.Add
'Saving the Workbook
ActiveWorkbook.SaveAs "C:\Users\iansch\Desktop\DummyWB.xlsx"
Set ws = wb.Sheets(1)
'what text to look for
TextToFind = "VALUE DATE"
'''''problems here below
Set rng1 = oWordApp.ActiveDocument.Content
rng.Find.Execute findtext:=TextToFind, Forward:=True
If rng1.Find.found Then
If rng1.Information(wdwithintable) Then
TheContent = rng.Cells(1).Next.Range.Text 'moves right on row
End If
Else
MsgBox "Text '" & TextToFind & "' was not found!"
End If
'copy text range and paste into cell A1
'tbl.range.copy
ws.Range("A1").Activate
ws.Paste
End Sub
At the line
set rng1.oWordApp.ActiveDocument.Content
I get a run-time 8002801d error - automation error, library not registered.
I couldn't find anything on here that was perfect for my case, however the 2nd question I linked to is very, very close to what I want, however I'm trying to import text rather than a table.
This will extract the "X,XXX.XX" value into a new Excel file, sheet 1, cell A1:
Option Explicit
Public Sub wordscraper9000()
Const FIND_TXT As String = "VALUE DATE"
Const OUTPUT As String = "\DummyWB.xlsx"
Dim fName As Variant, wrdApp As Object, wrdTxt As Variant, sz As Long, wb As Workbook
fName = Application.GetOpenFilename("Word Files (*.Doc*),*.Doc*", , _
"Enter filepath of .doc with desired information")
If fName <> False Then
'get Word text --------------------------------------------------------------------
On Error Resume Next
Set wrdApp = GetObject(, "Word.Application")
If Err.Number <> 0 Then
Set wrdApp = CreateObject("Word.Application")
Err.Clear
End If: wrdApp.Visible = False
wrdTxt = wrdApp.Documents.Open(fName).Content.Text: wrdApp.Quit
'get value ------------------------------------------------------------------------
sz = InStr(1, wrdTxt, FIND_TXT, 1)
If Len(sz) > 0 Then
wrdTxt = Trim(Right(wrdTxt, Len(wrdTxt) - sz - Len(FIND_TXT)))
wrdTxt = Split(Trim(Right(wrdTxt, InStr(wrdTxt, " "))))(0)
'save to Excel ----------------------------------------------------------------
Set wb = Workbooks.Add
wb.Sheets(1).Cells(1, 1) = wrdTxt
Application.DisplayAlerts = False
wb.Close True, CreateObject("WScript.Shell").SpecialFolders("Desktop") & OUTPUT
Application.DisplayAlerts = True
End If
End If
End Sub
.
This code is specific to this pattern:
"Reference" (any # of spaces) (any word without a space) (any # of spaces) "ExtractValue"
Search for reference (FIND_TXT)
Find and skip the next word (text without a space in it) after any number of spaces or empty lines
Extract the second word, separated by any number of spaces or lines from the skipped first word
Modifying your code a bit and if the information you want is in a fixed position within a Word table, you can do this:
Sub wordscraper90000()
Dim oWordApp As Object, oWordDoc As Object
Dim FlName As String
Dim TheContent As String
FlName = Application.GetOpenFilename("Word Files (*.Doc*),*.Doc*", , _
"Enter filepath of .doc with desired information")
'establish word app object
On Error Resume Next
Set oWordApp = GetObject(, "Word.application")
If Err.Number <> 0 Then
Set oWordApp = CreateObject("Word.application")
End If
Err.Clear
On Error GoTo 0
oWordApp.Visible = True
'open word doc
Set oWordDoc = oWordApp.Documents.Open(FlName)
'declare excel objects
Dim wb As Workbook, ws As Worksheet
'Adding New Workbook
Set wb = Workbooks.Add
'Saving the Workbook
ActiveWorkbook.SaveAs "C:\Users\iansch\Desktop\DummyWB.xlsx"
Set ws = wb.Sheets(1)
TheContent = oWordDoc.Tables.Item(1).Cell(2, 3).Range.Text
ws.Range("A1").Activate
ws.Range("A1").Value = Trim(Replace(TheContent, Chr(7), Chr(32))) 'Remove strange character at the end
End Sub
Whereas the data to be extracted it is in row 2, column 3: