I am searching for a string in a table inside a PDF file using a VBA script. The script is working when called from Word but not when called from Excel.
My PDF has many tables and the goal is to get the table number of the table containing a specific string.
Sub FindTableno()
Dim oTbl As Table
Dim oRow As Row
Dim oCell As Cell
Dim tblno As Integer
On Error Resume Next
' Create a "FileDialog" object as a File Picker dialog box.
Dim fd As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
Dim sfileName As String
With fd
.AllowMultiSelect = False
.Filters.Clear
.Title = "Select a PDF File"
.Filters.Add "All PDF Documents", "*.pdf?", 1
If .Show = True Then
sfileName = Dir(.SelectedItems(1)) ' Get the file.
End If
End With
Application.ScreenUpdating = False
Application.DisplayAlerts = False
If Trim(sfileName) <> "" Then
Dim objWord As Object ' Create a Word object.
Set objWord = CreateObject("Word.Application")
objWord.Visible = False ' Do not show the file.
' Create a Document object and open the Word file.
Dim objDoc As Word.Document
Set objDoc = objWord.Documents.Open(FileName:=fd.InitialFileName & sfileName, Format:="PDF Files", ConfirmConversions:=False)
' Search within tables in selected PDF file
objDoc.Activate
If ActiveDocument.Tables.Count > 0 Then
tblno = 1
For Each oTbl In ActiveDocument.Tables
For Each oRow In oTbl.Rows
For Each oCell In oRow.Cells
oCell.Select
Selection.Find.Execute FindText:="Nutrition Information"
If Selection.Find.Found = True Then
MsgBox (tblno)
Exit Sub
Else
End If
Next
Next
tblno = tblno + 1
Next
End If
MsgBox ("Not Found, Total Tables Searched:" & ActiveDocument.Tables.Count)
End If
Dim X As Variant
X = Shell("powershell.exe kill -processname winword", 1)
End Sub
The main issue is in this part where you use oCell.Select and afterwards Selection.Find. In this case Selection refers to the selected cell in Excel! This is because you didn't specifiy any relation to Word here, so Excel assumes you mean the selected cell in Excel.
I recommend to read How to avoid using Select in Excel VBA. The same is valid for Word VBA code.
Also don't use .Activate or you will get a similar issue. Always reference the worksheet or document directly:
If objDoc.Tables.Count > 0 Then
tblno = 1
For Each oTbl In objDoc.Tables
For Each oRow In oTbl.Rows
For Each oCell In oRow.Cells
oCell.Range.Find.Execute FindText:="Nutrition Information"
If oCell.Range.Find.Found = True Then
MsgBox (tblno)
Exit Sub
End If
Next
Next
tblno = tblno + 1
Next
End If
MsgBox ("Not Found, Total Tables Searched:" & objDoc.Tables.Count)
Thanks #Pᴇʜ, this worked for me
Sub FindTableno()
Dim oTbl As Table
Dim oRow As Row
Dim oCell As Cell
Dim tblno As Integer
' Create a "FileDialog" object as a File Picker dialog box.
Dim fd As Office.FileDialog
Set fd = Application.FileDialog(msoFileDialogFilePicker)
Dim sfileName As String
With fd
.AllowMultiSelect = False
.Filters.Clear
.Title = "Select a PDF File"
.Filters.Add "All PDF Documents", "*.pdf?", 1
If .Show = True Then
sfileName = Dir(.SelectedItems(1)) ' Get the file.
End If
End With
Application.ScreenUpdating = True
Application.DisplayAlerts = True
If Trim(sfileName) <> "" Then
Dim objWord As Object ' Create a Word object.
Set objWord = CreateObject("Word.Application")
objWord.Visible = True ' Do not show the file.
' Create a Document object and open the Word file.
Dim objDoc As Word.Document
'Set objDoc = objWord.Documents.Open(Filename:=fd.InitialFileName & sfileName, Format:="PDF Files", ConfirmConversions:=False)
Set objDoc = objWord.Documents.Open(Filename:=fd.InitialFileName & sfileName, Format:="PDF Files", ConfirmConversions:=False)
' Search within tables in selected PDF file
If objDoc.Tables.count > 0 Then
tblno = 1
For Each oTbl In objDoc.Tables
For Each oRow In oTbl.Rows
For Each oCell In oRow.Cells
pos = InStr(oCell.Range.Text, "Nutrition Information ")
If pos <> 0 Then
GoTo line1
End If
'Else
'End If
Next
Next
tblno = tblno + 1
Next
End If
MsgBox ("Not Found, Total Tables Searched:" & objDoc.Tables.count)
'MsgBox (oCell.Range.Text)
End If
line1:
MsgBox (tblno)
End Sub
Related
I have a Word file that has table with 5 columns: Step, Document, Doc #, Compo and Lot #, Sign, Date. I need to search for "Lot #" and "E#" in the word file then get the Step number, the text of row contains the string into an Excel file. I found a code that need to have the keywords in Sheet 1 of Excel then extract the data from Word into Sheet 2 with 1st column as keyword, 2nd column as row number in Word and 3rd column is the text of that row.
Is there any way I can hard code the keywords with options/message box to choose the keyword into VBA module instead of Sheet 1 and get the data in Sheet 1 with 1st column as keyword, 2nd column as the value in Step column in Word and 3rd column is the text of that row?
I'm pretty new to VBA so I don't know how to implement those.
Sub LocateSearchItem()
Dim shtSearchItem As Worksheet
Dim shtExtract As Worksheet
Dim oWord As Word.Application
Dim WordNotOpen As Boolean
Dim oDoc As Word.Document
Dim oRange As Word.Range
Dim LastRow As Long ' last row with data in shtSearchItem
Dim CurrRowShtSearchItem As Long ' current row in shtSearchItem
Dim CurrRowShtExtract As Long ' current row in shtExtract
Dim myPara As Long
On Error Resume Next
Set oWord = GetObject(, "Word.Application")
wdFileName = Application.GetOpenFilename("Word files (*.docx),*.docx", , _
"Browse for file containing table to be imported")
If wdFileName = False Then Exit Sub '(user cancelled import file browser)
Set oDoc = GetObject(wdFileName) 'open Word file
If Err Then
Set oWord = New Word.Application
WordNotOpen = True
End If
On Error GoTo Err_Handler
oWord.Visible = True
oWord.Activate
Set shtSearchItem = ThisWorkbook.Worksheets(1)
If ThisWorkbook.Worksheets.Count < 2 Then
ThisWorkbook.Worksheets.Add After:=shtSearchItem
End If
Set shtExtract = ThisWorkbook.Worksheets(2)
LastRow = shtSearchItem.UsedRange.Rows(shtSearchItem.UsedRange.Rows.Count).Row
For CurrRowShtSearchItem = 2 To LastRow
Set oRange = oDoc.Range
With oRange.Find
.Text = shtSearchItem.Cells(CurrRowShtSearchItem, 1).Text
.MatchCase = False
.MatchWholeWord = True
While oRange.Find.Execute = True
oRange.Select
myPara = oDoc.Range(0, oWord.Selection.Paragraphs(1).Range.End).Paragraphs.Count
CurrRowShtExtract = CurrRowShtExtract + 1
shtExtract.Cells(CurrRowShtExtract, 1).Value = .Text
shtExtract.Cells(CurrRowShtExtract, 2).Value = myPara
shtExtract.Cells(CurrRowShtExtract, 3) = oDoc.Paragraphs(myPara).Range
oRange.Collapse wdCollapseEnd
Wend
End With
Next CurrRowShtSearchItem
If WordNotOpen Then
oWord.Quit
End If
'Release object references
Set oWord = Nothing
Set oDoc = Nothing
Exit Sub
Err_Handler:
MsgBox "Word caused a problem. " & Err.Description, vbCritical, "Error: " & Err.Number
If WordNotOpen Then
oWord.Quit
End If
End Sub
What I got from the current code
I have about 100 Word documents and from each I want to copy data and paste it all in one Excel workbook.
I came up with this code which opens one Word document, copies data, pastes it to Excel and closes the Word document:
Sub WordDataToExcel()
Dim myObj
Dim myWB
Dim mySh
Dim txt As String, Lgth As Long, Strt As Long
Dim i As Long
Dim oRng As Range
Dim Tgt As String
Dim TgtFile As String
Dim arr()
Dim ArrSize As Long
Dim ArrIncrement As Long
ArrIncrement = 1000
ArrSize = ArrIncrement
ReDim arr(ArrSize)
Dim wrdDoc As Object
Documents.Open ("D:\ekr5_i.doc")
TgtFile = "result.xlsx"
Tgt = "D:\" & TgtFile
'finds the text string of Lgth lenght
txt = "thetext"
Lgth = 85
Strt = Len(txt)
'Return data to array
With Selection
.HomeKey unit:=wdStory
With .Find
.ClearFormatting
.Forward = True
.Text = txt
.Execute
While .Found
i = i + 1
Set oRng = ActiveDocument.Range _
(Start:=Selection.Range.Start + Strt, _
End:=Selection.Range.End + Lgth)
arr(i) = oRng.Text
oRng.Start = oRng.End
.Execute
If i = ArrSize - 20 Then
ArrSize = ArrSize + ArrIncrement
ReDim Preserve arr(ArrSize)
End If
Wend
End With
End With
ReDim Preserve arr(i)
'Set target and write data
Set myObj = CreateObject("Excel.Application")
Set myWB = myObj.Workbooks.Open(Tgt)
Set mySh = myWB.Sheets(1)
With mySh
.Range(.Cells(1, 1), .Cells(i, 1)) = myObj.Transpose(arr)
End With
'Tidy up
myWB.Close True
myObj.Quit
ActiveDocument.Close SaveChanges:=wdDoNotSaveChanges
Set mySh = Nothing
Set myWB = Nothing
Set myObj = Nothing
End Sub
I need to loop through all the documents in the folder.
I have implemented the same with Excel workbooks, but I don't know how for Word documents.
Here is the code for Excel workbooks:
Sub combine_into_one()
Dim FSO As Object: Set FSO = CreateObject("Scripting.FileSystemObject")
Dim strPath$, Pivot$, sUserName$, sFolderName$, sSourceName$, x&
Dim oFldialog As FileDialog
Dim oFolder
Application.DisplayAlerts = False
Application.ScreenUpdating = False
Set oFldialog = Application.FileDialog(msoFileDialogFolderPicker)
With oFldialog
If .Show = -1 Then
.Title = "Select a Folder"
.AllowMultiSelect = False
.InitialFileName = strPath
sFolderName = .SelectedItems(1)
End If
End With
Set oFolder = FSO.GetFolder(sFolderName)
Workbooks.Add: Pivot = ActiveWorkbook.Name 'Destination workbook
For Each oFile In oFolder.Files
Workbooks(Pivot).Activate
x = Workbooks(Pivot).Sheets(1).Cells.SpecialCells(xlCellTypeLastCell).Row + 1
Workbooks.Open Filename:=oFile: sSourceName = ActiveWorkbook.Name
Workbooks(sSourceName).Activate
Workbooks(sSourceName).Sheets(1).[A80:Q94].copy
Workbooks(Pivot).Activate
Workbooks(Pivot).Sheets(1).Cells(x + 1, 1).PasteSpecial xlPasteAll
Workbooks(sSourceName).Close False
Next
Application.CutCopyMode = False
Application.DisplayAlerts = True
Application.ScreenUpdating = True
End Sub
There are so, so, so many things you can do between Excel & Word. I'm not sure I totally understand your question. The script below may help you; it has definitely served me well over time. If you need something different, please describe your issue more, to better clarify the issue you are facing.
Sub OpenAndReadWordDoc()
Rows("2:1000000").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.ClearContents
Range("A1").Select
' assumes that the previous procedure has been executed
Dim oWordApp As Word.Application
Dim oWordDoc As Word.Document
Dim blnStart As Boolean
Dim r As Long
Dim sFolder As String
Dim strFilePattern As String
Dim strFileName As String
Dim sFileName As String
Dim ws As Worksheet
Dim c As Long
Dim n As Long
'~~> Establish an Word application object
On Error Resume Next
Set oWordApp = GetObject(, "Word.Application")
If Err Then
Set oWordApp = CreateObject("Word.Application")
' We started Word for this macro
blnStart = True
End If
On Error GoTo ErrHandler
Set ws = ActiveSheet
r = 1 ' startrow for the copied text from the Word document
' Last column
n = ws.Range("A1").End(xlToRight).Column
sFolder = "C:\Users\Excel\Desktop\Coding\Microsoft Excel\PWC\Resumes\"
'~~> This is the extension you want to go in for
strFilePattern = "*.doc*"
'~~> Loop through the folder to get the word files
strFileName = Dir(sFolder & strFilePattern)
Do Until strFileName = ""
sFileName = sFolder & strFileName
'~~> Open the word doc
Set oWordDoc = oWordApp.Documents.Open(sFileName)
' Increase row number
r = r + 1
' Enter file name in column A
ws.Cells(r, 1).Value = sFileName
ActiveCell.Offset(1, 0).Select
ActiveSheet.Hyperlinks.Add Anchor:=Sheets("Sheet1").Range("A" & r), Address:=sFileName, _
SubAddress:="A" & r, TextToDisplay:=sFileName
' Loop through the columns
For c = 2 To n
If oWordDoc.Content.Find.Execute(FindText:=Trim(ws.Cells(1, c).Value), _
MatchWholeWord:=True, MatchCase:=False) Then
' If text found, enter Yes in column number c
ws.Cells(r, c).Value = "Yes"
End If
Next c
oWordDoc.Close SaveChanges:=False
'~~> Find next file
strFileName = Dir
Loop
ExitHandler:
On Error Resume Next
' close the Word application
Set oWordDoc = Nothing
If blnStart Then
' We started Word, so we close it
oWordApp.Quit
End If
Set oWordApp = Nothing
Exit Sub
ErrHandler:
MsgBox Err.Description, vbExclamation
Resume ExitHandler
End Sub
Function GetDirectory(path)
GetDirectory = Left(path, InStrRev(path, "\"))
End Function
In this scenario, whatever you put in the headers of B1:K1 (or more to the right) is searched for, each word document in a folder is opened, scanned, and if the string in B1:K1 is found, an 'x' is placed in the same x-y coordinate.
Again, if this doesn't help, please describe your issue better, and I'll post back with alternative solutions. Thanks!!
I am trying to copy text in Excel cells (cell A1 to A66) into a Word document. The goal of this operation is to copy it and paste it as TEXT. If copied directly from Excel, it will paste as a TABLE.
Private Sub Bouton1_Click()
Dim objWord As New Word.Application
With objWord
.Documents.Add
Application.Wait (Now + TimeValue("0:00:01") / 2)
Worksheets("Description2").Cells(1, 1).Copy
Application.Wait (Now + TimeValue("0:00:01") / 2)
.Selection.PasteSpecial xlPasteValues
.Visible = True
End With
Dim i As Integer
For i = 2 To 66
If Worksheets("Description2").Cells(i, 1) = Worksheets("Description2").Cells(i + 1, 1) Then Exit For
With objWord
Application.Wait (Now + TimeValue("0:00:01") / 2)
Worksheets("Description2").Cells(i, 1).Copy
Application.Wait (Now + TimeValue("0:00:01") / 2)
.Selection.PasteSpecial xlPasteValues
.Visible = True
End With
Next i
objWord.Application.Activate
objWord.Application.WindowState = wdWindowStateMaximize
End Sub
This code works about 70% of the time. When it doesn't work, I get this error (or a variation, but always concerning the clipboard):
Run-Time error "4605": This method or property is not available
because the clipboard is empty or not valid.
Also, sometimes a random OneDrive window opens.
I've added the Application.Wait lines to try to slow down the copy/paste, but it doesn't do that much.
How can I make my code more reliable?
If you want to paste as text, perhaps:
Sub CopyAsTextToWord()
Dim wordApp As New Word.Application
With wordApp
.Visible = True
.Documents.Add
Worksheets("Description2").Range("A1:A66").Copy
.Selection.PasteSpecial DataType:=wdPasteText
End With
End Sub
If on the other hand you want to paste each cell one at a time (this is what it seems like from your original code, not sure), perhaps a slightly different approach, avoiding the clipboard. Read the range into an array, iterate through it and then use Selection.TypeText to "paste" each element sequentially. Probably can be made more robust.
Sub TransferAsText()
Dim wordApp As New Word.Application
With wordApp
.Visible = True
.Documents.Add
Dim arr()
arr = Worksheets("Description2").Range("A1:A66").Value
Dim i As Long
For i = LBound(arr, 1) To UBound(arr, 1)
.Selection.TypeText Text:=CStr(arr(i, 1))
Next i
End With
End Sub
Write a separate function and capture all data from Excel
Function GetDataFromExcel()
CreateObject ("Excel.Application")
Dim xlApp As Excel.Application, xObjFD As FileDialog
Set xlApp = New Excel.Application
xlApp.Visible = True
Set xObjFD = Application.FileDialog(msoFileDialogFilePicker)
xObjFD.Title = "Select the excel file location " & FileType
With xObjFD
.AllowMultiSelect = False
.Filters.Add "Excel Files", "*.xls; *.xlsx; *.xlsm; *.xlsb", 1
.Show
' Selection is not null
If .SelectedItems.Count > 0 Then
xFilePath = .SelectedItems.Item(1)
Else
Exit Function
End If
Dim xlWorkBook As Object, valueCollected As String, _
rowCount As Integer : rowCount = 1
Set xlWorkBook = xlApp.Workbooks.Open(xFilePath, True, False)
xlWorkBook.Activate
Set ArrayValues = New ArrayList
loopToCollectData:
On Error GoTo err
valueCollected = xlApp.ActiveWorkbook.Sheets("Description2").Range("A" & rowCount).Value
If valueCollected <> "" Then
ArrayValues.Add valueCollected
If rowCount < 66 then
rowCount = rowCount + 1
GoTo loopToCollectData
End If
End If
End With
xlWorkBook.Close
xlApp.Visible = False
Exit Function
err:
xlWorkBook.Close
xlApp.Visible = False
MsgBox "Please select the relevant input file!"
End
End Function
Once data is collected, then it is independent of the application and could be used inside the word application.
An Array could be also used to collect the data by using the range.
Function GetDataFromExcel()
' Some Code ===========
dataArrayCollected = Application.Transpose(Range(Cells(1, 1), Cells(66, 1)))
' Some more Code ===========
' No more code =========== 😃 😁
End Function
I have used the VBA macro below to put multiple tables from multiple Word documents into one worksheet in Excel.
I want the multiple tables from each different Word doc to go into different worksheets with the worksheets named the name of the Word doc.
Sub ImportWordTable()
Dim WordApp As Object
Dim WordDoc As Object
Dim arrFileList As Variant, FileName As Variant
Dim tableNo As Integer 'table number in Word
Dim tableStart As Integer
Dim tableTot As Integer
Dim Target As Range
'On Error Resume Next
arrFileList = Application.GetOpenFilename("Word files (*.doc; *.docx),*.doc;*.docx", 2, _
"Browse for file containing table to be imported", , True)
If Not IsArray(arrFileList) Then Exit Sub '(user cancelled import file browser)
Set WordApp = CreateObject("Word.Application")
WordApp.Visible = True
Range("A:AZ").ClearContents
Set Target = Range("A1")
For Each FileName In arrFileList
Set WordDoc = WordApp.Documents.Open(FileName, ReadOnly:=True)
With WordDoc
tableNo = WordDoc.tables.Count
tableTot = WordDoc.tables.Count
If tableNo = 0 Then
MsgBox WordDoc.Name & " contains no tables", vbExclamation, "Import Word Table"
ElseIf tableNo > 1 Then
tableNo = InputBox(WordDoc.Name & " contains " & tableNo & " tables." & vbCrLf & _
"Enter the table to start from", "Import Word Table", "1")
End If
For tableStart = 1 To tableTot
With .tables(tableStart)
.Range.Copy
'Target.Parent.PasteSpecial Format:="Text", Link:=False, DisplayAsIcon:=False
Target.Activate
ActiveSheet.Paste
Set Target = Target.Offset(.Rows.Count + 2, 0)
End With
Next tableStart
.Close False
End With
Next FileName
WordApp.Quit
Set WordDoc = Nothing
Set WordApp = Nothing
End Sub
Try the following macro. It allows you to choose the source folder. It creates a new worksheet for each document and outputs all tables from that document one below the other, with an empty row in between. Except for text wrapping, table formatting is preserved as much as possible.
Sub GetTableData()
'Note: this code requires a reference to the Word object model.
'See under the VBE's Tools|References.
Application.ScreenUpdating = False
Dim wdApp As New Word.Application, wdDoc As Word.Document, wdTbl As Word.Table
Dim strFolder As String, strFile As String, WkBk As Workbook, WkSht As Worksheet, r As Long
strFolder = GetFolder: If strFolder = "" Then GoTo ErrExit
Set WkBk = ActiveWorkbook
'Disable any Word Alerts
wdApp.DisplayAlerts =wdAlertsNone
'Disable any auto macros in the documents being processed
wdApp.WordBasic.DisableAutoMacros
strFile = Dir(strFolder & "\*.doc", vbNormal)
While strFile <> ""
Set wdDoc = wdApp.Documents.Open(Filename:=strFolder & "\" & strFile, ReadOnly:=True, AddToRecentFiles:=False, Visible:=False)
Set WkSht = WkBk.Sheets.Add
WkSht.Name = Split(strFile, ".doc")(0)
With wdDoc
For Each wdTbl In .Tables
With wdTbl.Range.Find
.ClearFormatting
.Replacement.ClearFormatting
.Text = "[^13^l]"
.Replacement.Text = "¶"
.Forward = True
.Wrap = wdFindStop
.Format = False
.MatchWildcards = True
.Execute Replace:=wdReplaceAll
End With
r = WkSht.Cells(WkSht.Rows.Count, 1).End(xlUp).Row
If r > 1 Then r = r + 2
wdTbl.Range.Copy
WkSht.Paste Destination:=WkSht.Range("A" & r)
Next
WkSht.UsedRange.Replace What:="¶", Replacement:=Chr(10), LookAt:=xlPart, SearchOrder:=xlByRows
.Close SaveChanges:=False
End With
strFile = Dir()
Wend
ErrExit:
wdApp.Quit
Set wdDoc = Nothing: Set wdApp = Nothing: Set WkSht = Nothing: Set WkBk = 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
Something like the following, perhaps. Since I can't replicate your documents my test environment wasn't identical...
The following code declares a Word.Table and a Excel.Worksheet object to the list of declared variables.
The Worksheet object is set to ActiveSheet and later to each added worksheet. Using an object instead of a selection or "active" something is almost always preferable - then it's clearer for both human and VBA what's is meant. ws is also used to more exactly define the Range specifications.
Before looping the tables, the worksheet Name is set to the value stored in Filename for the Word document.
The Table object is set to the WordDoc.tables(tableStart) table. It's more efficient to work with an object instead of querying the full "path" to an object each time. It's also easier to read.
Before looping to the next Word document a new worksheet is added.
Sub ImportWordTable()
Dim WordApp As Object
Dim WordDoc As Object
Dim tbl As Object
Dim arrFileList As Variant, FileName As Variant
Dim tableNo As Integer 'table number in Word
Dim tableStart As Integer
Dim tableTot As Integer
Dim ws As Worksheet
Dim Target As Range
'On Error Resume Next
arrFileList = Application.GetOpenFilename("Word files (*.doc; *.docx),*.doc;*.docx", 2, _
"Browse for file containing table to be imported", , True)
If Not IsArray(arrFileList) Then Exit Sub '(user cancelled import file browser)
Set WordApp = CreateObject("Word.Application")
WordApp.Visible = True
Set ws = ActiveSheet
ws.Range("A:AZ").ClearContents
For Each FileName In arrFileList
Set WordDoc = WordApp.Documents.Open(FileName, ReadOnly:=True)
With WordDoc
tableNo = WordDoc.tables.Count
tableTot = WordDoc.tables.Count
If tableNo = 0 Then
MsgBox WordDoc.Name & " contains no tables", vbExclamation, "Import Word Table"
ElseIf tableNo > 1 Then
tableNo = InputBox(WordDoc.Name & " contains " & tableNo & " tables." & vbCrLf & _
"Enter the table to start from", "Import Word Table", "1")
End If
ws.Name = FileName
For tableStart = 1 To tableTot
Set Target = ws.Range("A1")
Set tbl = .tables(tableStart)
With tbl
.Range.Copy
'Target.Parent.PasteSpecial Format:="Text", Link:=False, DisplayAsIcon:=False
Target.Activate
ws.Paste
Set Target = Target.Offset(.Rows.Count + 2, 0)
End With
Next tableStart
.Close False
End With
Set ws = ws.Parent.Worksheets.Add
Next FileName
ws.Delete 'the last sheet is one too many
WordApp.Quit
Set WordDoc = Nothing
Set WordApp = Nothing
End Sub
I have about a dozen linked excel OLE objects in my word document. These files get moved around the network frequently so I need an easy intuitive way for the underlying links to be updated. I tried a code I found on this website however while it updated the source it seems to also update what is being shown in the object itself so all the objects change to whatever worksheet was in focus when the excel workbook was saved last. I'm trying to retain format and range while updating the source. Any help would be great.
Here is the code I tried presently:
Private Sub CommandButton1_Click()
Dim OldFile As String
Dim xlsobj As Object
Dim xlsfile_chart As Object
Dim dlgSelectFile As FileDialog 'FileDialog object '
Dim thisField As Field
Dim selectedFile As Variant
'must be Variant to contain filepath of selected item
Dim newFile As Variant
Dim fieldCount As Integer '
Dim x As Long
On Error GoTo LinkError
'create FileDialog object as File Picker dialog box
Set dlgSelectFile = Application.FileDialog
(FileDialogType:=msoFileDialogFilePicker)
With dlgSelectFile
.Filters.Clear 'clear filters
.Filters.Add "Microsoft Excel Files", "*.xls, *.xlsb, *.xlsm,*.xlsx" 'filter
for only Excel files
'use Show method to display File Picker dialog box and return user's action
If .Show = -1 Then
'step through each string in the FileDialogSelectedItems collection
For Each selectedFile In .SelectedItems
newFile = selectedFile 'gets new filepath
Next selectedFile
Else 'user clicked cancel
Exit Sub
End If
End With
Set dlgSelectFile = Nothing
'update fields
Set xlsobj = CreateObject("Excel.Application")
xlsobj.Application.Visible = False
Set xlsfile_chart = xlsobj.Application.Workbooks.Open(newFile, ReadOnly =
True)
Application.ScreenUpdating = False
With xlsobj.Application
.calculation = xlcalculationmanual
.enableevents = False
End With
fieldCount = ActiveDocument.Fields.Count
For x = 1 To fieldCount
With ActiveDocument.Fields(x)
If .Type = 56 Then
.LinkFormat.SourceFullName = newFile
End If
End With
Next x
With xlsobj.Application
.calculation = xlcalculationmanual
.enableevents = True
End With
Application.ScreenUpdating = True
MsgBox "Data has been sucessfully linked to report"
'clean up
xlsfile_chart.Close SaveChanges:=False
Set xlsfile_chart = Nothing
xlsobj.Quit
Set xlsobj = Nothing
Exit Sub
LinkError:
Select Case Err.Number
Case 5391 'could not find associated Range Name
MsgBox "Could not find the associated Excel Range Name " & _
"for one or more links in this document. " & _
"Please be sure that you have selected a valid " & _
"Quote Submission input file.", vbCritical
Case Else
MsgBox "Error " & Err.Number & ": " & Err.Description, vbCritical
End Select
' clean up
Set xlsfile_chart = Nothing
xlsobj.Quit
Set xlsobj = Nothing
End Sub