how to use an already open document from another module? - vba

i write in a word.document. When it is necessary i write a paragraph in another document and when i finish this document is closed. then i try to copy this paragraph to the first document which remains open.
I try some things but in vain.
when i do this:
Dim wdDocMain As Word.Document
Set wdDocMain = ActiveDocument
i receive the message run time error 4248 This command is not available because no document is open.
when i do this
Dim wdDocMain As Word.Document
Set wdDocMain = wdApp.Documents.Open(FileName:=pathmaindoc,_ ReadOnly:=False, Visible:=True)
wdDocMain.Activate
i receive the message run time error 91 object variable or with block variable not set.
i find a solution.
To close the open document and then to reopen it like this:
Set wdDocMain = wdApp.Documents.Open(FileName:=pathmaindoc,_ ReadOnly:=False, Visible:=True)
but of cource it isnt the best.
Edit.
I would like to thank you in advance for your comments.
i share more lines from my code as Timothy Rylatt suggested.
In my main sub:
Dim wdapp As Word.Application
Dim wdDoc As Word.Document
Set wdapp = New Word.Application
Set wdDoc = wdapp.Documents.Open(FileName:=PathName_HiveDown_Creation,_ ReadOnly:=False, Visible:=True)
wdapp.Visible = True
when a condition is met then i call a module (copyparafromtemplatetomain):
pathmaindoc = PathName_HiveDown_Creation
pathtemplatedoc = PathName_Template
'wdDoc.Close savechanges:=True
copyparafromtemplatetomain
Public wdapp As Word.Application
Public wdDocMain As Word.Document
Sub copyparafromtemplatetomain(pathmaindoc As Variant, pathtemplatedoc As Variant, paramain As Variant, paratemplate As Variant, index As Integer)
Dim wdDocTemplate As Word.Document
Dim PathName_MainDoc As Variant
PathName_MainDoc = pathmaindoc
Set wdDocMain = wdapp.ActiveDocument
here, i receive run time error 91.
the only way to run is when i close the doc. in the first sub

Related

VBA: Activate method not found

I have some VBA code that was working perfectly a few weeks ago, but now is crashing with an error. The code, which is triggered from Word, is meant to open an Excel file. The specific error I'm getting is related to the Activate method.
Sub Populate()
Dim eApp As Excel.Application
Dim eWB As Excel.Workbook
Dim eSheet As Excel.Worksheet
On Error Resume Next
Set eApp = GetObject(, "Excel.Application")
If Err Then
ExcelWasNotRunning = True
Set eApp = New Excel.Application
End If
'Open Workbook
WorkbookName = "(Excel file location)"
eApp.Visible = True
eApp.Activate
Set eWB = eApp.Workbooks.Open(WorkbookName)
eWB.Activate
(etc.)
I'm a VBA novice so I'm sure there's a better way to write the above. It's the final line - eWB.Activate - that creates a compile error, "Method or data member not found." Again, this was working last month and isn't working now. Has something changed in Office 2016 that makes this code illegal?
I played around and think I have a workaround, but I'd still like to know why this is crashing, for future reference. Thanks.
EDIT: Here is the error
Do not know why you have that Error when you have On Error Resume Next from there on. Are there codes missing from what you have posted? Also is the Excel workbook macro enabled that may interfere the codes in Word?
You may also try Late Binding for those Excel Objects once you are done coding with IntelliSense. Just to demonstrate how I would code this Excel file open part (Excel 2010):
Option Explicit
Sub Populate()
Dim eApp As Object ' Excel.Application
Dim eWB As Object ' Excel.Workbook
Dim eSheet As Object ' Excel.Worksheet
Dim ExcelWasNotRunning As Boolean
Dim WorkbookName As String
On Error Resume Next
Set eApp = GetObject(, "Excel.Application")
If eApp Is Nothing Then Set eApp = CreateObject("Excel.Application")
ExcelWasNotRunning = eApp Is Nothing
If ExcelWasNotRunning Then Exit Sub
'Open Workbook
WorkbookName = "C:\Test\Tables.xlsx"
eApp.Visible = True
'eApp.Activate
Set eWB = eApp.Workbooks.Open(WorkbookName)
On Error GoTo 0 ' Turns on Debug prompt on Error
If Not eWB Is Nothing Then
With eWB
.Activate
' process stuff
.Save
.Close
End With
Set eWB = Nothing
End If
eApp.Quit
Set eApp = Nothing
End Sub
I ran this from word and it worked, I think somehow you have an early binding problem, which is most likely is due to installing a new version of word on your machine. You can google it and clean your registry to get rid of it.
Sub Populate()
Dim eApp As Object
Dim eWB As Object
Dim eSheet As Object
On Error Resume Next
Set eApp = GetObject(, "Excel.Application")
If Err Then
ExcelWasNotRunning = True
Set eApp = CreateObject("Excel.Application")
End If
'Open Workbook
WorkbookName = "\\grid\sasprod\ci\reports\Quickmarks\Quickmarks Tables A.xlsx"
eApp.Visible = True
eApp.Activate
Set eWB = eApp.Workbooks.Open(WorkbookName)
eWB.Activate
End Sub

VBA excel nesting data from excel into a table in word (copying excel data into Word table)

I'm trying to paste a table into word from excel with VBA Excel.
I'm pasting it into a cell in a single column table of 4 rows I created in Word. So it is essentially a nested table.
I keep getting,
Run-time error 4605: Method 'PasteAsNestedTable' of object Selection failed
I'm trying to use PastAsNestedTable because otherwise I get the Run-time error about cells not matching as it is trying to merge the two tables.
So I get it is saying PasteAsNestedTable isn't a method of selection but how do I get around this issue?
My updated code goes:
Dim wdApp As Word.Application
Dim wdDoc as Word.Document
Dim tabl1 as Table, tabl2 as Table
Set wdApp = new Word.Application
With wdApp
.visible = True
.Activate
.Document.Add(location)
Set wdDoc=wdApp.ActiveDocument
With wdApp
Charts("chart1").ChartArea.Copy
.Selection.GoTo what:=-1,Name:="chart1"
.selection.Paste
(Then add some more charts)
End With
Sheets("Sheet1").Range("A1:F10").Copy
Set wdDoc=wdApp.ActiveDocument
wdDoc.Bookmarks("table").Range.PasteAsNestedTable
With wdApp
(Then repeat above pasting charts + tables)
`
If I made the Range a ListObjects could I somehow copy it in that way?
Don't use Selection.
This here works for me (Word with correct document already opened):
Dim wdApp As Word.Application
Dim wdDoc As Word.Document
Set wdApp = GetObject(, "Word.Application")
Sheets(1).Range("A1:F10").Copy
Set wdDoc = wdApp.ActiveDocument
wdDoc.Bookmarks("tableplace").Range.PasteAsNestedTable
You can of course replace GetObject(, "Word.Application") with your new Word.Application and set wdDoc as wdApp.Documents.Open(pathtoyourdoc).
Then combine with my answer from your other thread, replace wdthere with wdDoc and you should be good to go.
Edit I have changed my code to reflect your current variables and bookmark names:
Dim wdApp As Word.Application
Dim wdDoc As Word.Document
Dim tabl1 As Table, tabl2 As Table
Set wdApp = New Word.Application
With wdApp
.Visible = True
.Activate
Set wdDoc = .Documents.Open(Location)
End With
Charts("chart1").ChartArea.Copy
wdDoc.Bookmarks("chart1").Range.Paste
Sheets("Sheet1").Range("A1:F10").Copy
wdDoc.Bookmarks("table").Range.PasteAsNestedTable
'(Continue like this for other charts + tables)
Note:
Do not use Douments.Add, as this will add a new empty document based on a template. This will not have your bookmarks. Use .Open instead.
Close With blocks properly
Do not set the same object over and over again. Set it once and work with that object
Do not use Selection unless absolutely necessary. Not necessary in this case.
You can set DocVariables in Word. Google this if you don't know how to do this. Then, run the script below, from Excel.
Sub PushToWord()
Dim objWord As New Word.Application
Dim doc As Word.Document
Dim bkmk As Word.Bookmark
sWdFileName = Application.GetOpenFilename(, , , , False)
Set doc = objWord.Documents.Open(sWdFileName)
'On Error Resume Next
objWord.ActiveDocument.variables("FirstName").Value = Range("FirstName").Value
objWord.ActiveDocument.variables("LastName").Value = Range("LastName").Value
objWord.ActiveDocument.variables("Another").Value = Range("Another").Value
objWord.ActiveDocument.Fields.Update
'On Error Resume Next
objWord.Visible = True
End Sub

Insert Hyperlink in Outlook body

So I am trying to create a code to expedite inserting a hyperlink in Outlook.
I am trying to have it so that if I have already copied a path, I can just go in and type Ctrl W and it will insert the hyperlink for the word here. My attempt at the code is:
Sub InsertHyperlink()
'
'
'
On Error Resume Next
ActiveDocument.Hyperlinks.Add Anchor:=Selection.Range, Address:= _
"U:\plot.log", _
SubAddress:="", ScreenTip:="", TextToDisplay:="here"
End Sub
I am having issues on how to update my code so that will work in Outlook (I programmed it in Word) and so that the "U:\plot.log" would actually be the copied path (not the copied path when I recorded the macro).
Does anyone have any suggestions?
Set your references to Word object Library
Tools > References > add Word object Library
Option Explicit
Sub Add_Hyperlinks()
Dim olNameSpace As Outlook.NameSpace
Dim wDoc As Word.Document
Dim rngSel As Word.Selection
If Application.ActiveInspector.EditorType = olEditorWord Then
Set wDoc = Application.ActiveInspector.WordEditor ' use WordEditor
Set olNameSpace = Application.Session
Set rngSel = wDoc.Windows(1).Selection ' Current selection
wDoc.Hyperlinks.Add rngSel.Range, _
Address:="U:\plot.log", TextToDisplay:="Here is the link"
End If
Set wDoc = Nothing
Set olNameSpace = Nothing
End Sub
Thank you so much for the help, I really appreciate it! So I made a slight variation to your code to try and get it to paste whatever is on the clipboard.
My new code is as follows. Do I need to add in any error trapping? Also, what does the option explicit exactly do?
Option Explicit
Sub Add_Hyperlinks()
Dim olNameSpace As Outlook.NameSpace
Dim wDoc As Word.Document
Dim rngSel As Word.Selection
Dim DataObj As MSForms.DataObject
Set DataObj = New MSForms.DataObject
DataObj.GetFromClipboard
If Application.ActiveInspector.EditorType = olEditorWord Then
Set wDoc = Application.ActiveInspector.WordEditor ' use WordEditor
Set olNameSpace = Application.Session
Set rngSel = wDoc.Windows(1).Selection ' Current selection
wDoc.Hyperlinks.Add rngSel.Range, _
Address:=DataObj.GetText(1), TextToDisplay:="here"
End If
Set wDoc = Nothing
Set olNameSpace = Nothing
End Sub

How to make sure from Excel that a specific Word document is open or not?

I wanted my excel macro to create a report by inserting spreadsheet data after Bookmarks I placed in the template word documents.
But I found out that if the template word document is already open, the macro will crash, and consequently the template document will be locked as Read-only and no longer accessible by the macro.
Is there a way to prevent then macro from crashing even if the template word document is already open?
Below is my code
Set wdApp = CreateObject("Word.Application") 'Create an instance of word
Set wdDoc = wdApp.Documents.Open(ThisWorkbook.Path & "\Templates\Template_Confirmation.docx") 'Create a new confirmation note
Here comes an evolution of what was suggested in comments :
A function that test if the file is open and offer you to set it directly while testing.
How to use it :
Sub test()
Dim WdDoc As Word.Document
Set WdDoc = Is_Doc_Open("test.docx", "D:\Test\")
MsgBox WdDoc.Content
WdDoc.Close
Set WdDoc = Nothing
End Sub
And the function :
Public Function Is_Doc_Open(FileToOpen As String, FolderPath As String) As Word.Document
'Will open the doc if it isn't already open and set an object to that doc
Dim wrdApp As Word.Application
Dim wrdDoc As Word.Document
On Error Resume Next
'Set wrdApp = GetObject(, "Word.Application")
If wrdApp Is Nothing Then
Set wrdApp = CreateObject("Word.Application")
Set wrdDoc = wrdApp.Documents.Open(FolderPath & FileToOpen)
Else
On Error GoTo NotOpen
Set wrdDoc = wrdApp.Documents(FileToOpen)
GoTo OpenAlready
NotOpen:
Set wrdDoc = wrdApp.Documents.Open(FolderPath & FileToOpen)
End If
OpenAlready:
On Error GoTo 0
Set Is_Doc_Open = wrdDoc
Set wrdApp = Nothing
Set wrdDoc = Nothing
End Function
Only downside of this, you don't have the reference of the Word application...
Any suggestion/evolution are welcome!

VBA Type mismatch error when setting Excel Range in Word

I have the following code as part of my sub trying to assign a range:
'Set xlApp = CreateObject("Excel.Application")
Dim xlApp As Object
Set xlApp = GetObject(, "Excel.Application")
xlApp.Visible = False
xlApp.ScreenUpdating = False
Dim CRsFile As String
Dim CRsMaxRow As Integer
' get the CR list
CRsFile = "CRs.xls"
Set CRsWB = xlApp.Workbooks.Open("C:\Docs\" + CRsFile)
With CRsWB.Worksheets("Sheet1")
.Activate
CRsMaxRow = .Range("A1").CurrentRegion.Rows.Count
Set CRs = .Range("A2:M" & CRsMaxRow)
End With
Dim interestingFiles As Range
' get the files names that we consider interesting to track
Set FilesWB = xlApp.Workbooks.Open("files.xlsx")
With FilesWB.Worksheets("files")
.Activate
Set interestingFiles = .Range("A2:E5")
End With
Do you have any idea why am I getting a run time type mismatch error?
If you run the code from Word then the problem is in the declaration of 'interestingFiles' variable. Range exist in Word as well so use either Variant or add reference to Excel and then use Excel.Range.
Without Excel reference:
Dim interestingFiles As Variant
And with Excel reference:
Dim interestingFiles As Excel.Range
Kindly set xlApp object as in below code.
Also you provide complete path for your workbook when opening it.
Sub test()
Dim interestingFiles As Range
Dim xlApp As Object
Set xlApp = GetObject(, "Excel.Application")
' get the files names
Dim path As String
path = "C:\Users\Santosh\Desktop\file1.xlsx"
Set FilesWB = xlApp.Workbooks.Open(path)
With FilesWB.Worksheets(1)
.Activate
Set interestingFiles = .Range("A2:E5")
End With
End Sub