1

I have a little bit of an issue that i can't solve.

I have programmed VBA code to export cell data from excel into word textboxes.

How it works: I have a button in the excel doc you highlight the row you want to work with you press the button it than grabs the data from all the cells i have told it to and imports them into word.

The problem i am having that is if I select another row and press the button again it tries to open that same word doc again and errors as it is already open. Is there anyway i can do and if statement to check to see if its open if its not open it and if it is use the active word doc?

here is my current code

Set objWord = CreateObject("Word.Application")
objWord.Visible = True
objWord.Documents.Open "C:\Users\swhiston\Desktop\IT Services Invoice.docx"

Thanks GreatSc0tt

GreatSc0tt
  • 11
  • 1
  • 3

2 Answers2

1

You want the Word object to by declared at Module/Class level and test whether or not it's already open before you open it

Option Explicit
Dim objWord As Object
Dim objDoc as Object

Sub OpenWord()

    Set objWord = CreateObject("Word.Application")
    objWord.Visible = True
    set objDoc = objWord.Documents.Open( "C:\Users\swhiston\Desktop\IT Services Invoice.docx")

End Sub


Sub MyCodeHere()

    'Open Word If It's Not Already Open
    If objwork Is Nothing Then OpenWord
    'Your Code Here

End Sub
Jiminy Cricket
  • 1,377
  • 2
  • 15
  • 24
  • Adding a document variable would be very helpful (necessary) with that kind of structure. ;) – R3uK Mar 10 '17 at 14:02
0

whenever you try to execute your code it will reopen the same file so either apply a condition that checks if file is open or not and if not then only it opens the file or every time you should close the file at the end of your code.

you can refer: Detect whether Excel workbook is already open

keep this in else part:

objWord.Documents.Open "C:\Users\swhiston\Desktop\IT Services Invoice.docx"
Community
  • 1
  • 1
Srijan
  • 142
  • 11
  • I am a n00b with VBA. Just learning. I am not sure how to test to see if its open – GreatSc0tt Mar 10 '17 at 13:41
  • So this was a huge help sir. Right now i have it so that if the word doc is open is show a message telling them to close it. If nothing is open then it goes to else and runs my code to open it. The problem I am still having is how to use the open word document. I was to keep adding exports from excel to word – GreatSc0tt Mar 10 '17 at 17:09
  • @GreatSc0tt - OK in the code where it has msgbx written write your code and you can refer the open word file by using variable objword that you have used as object – Srijan Mar 14 '17 at 08:21