Bypass workbook_open when opening from word - vba

I am working on a project that requires both an excel document and a word document. I have fully programmed the excel document to work using UserForms, one of which opens automatically when opening the document. (see code below)
Private Sub Workbook_Open()
frmOpen.Show
End Sub
The word document has been programmed to read data from this excel document and write it into a report. (see code below)
Private Sub cmdAutomatic_Click()
Dim objExcel As New Excel.Application
Dim exWb As Excel.Workbook
Dim selectID As String
Set exWb =objExcel.Workbooks.Open("C:\ Path")
exWb.Close
''Data is written into the document here
Set exWb = Nothing
Unload Me
End Sub
The issue is that every time this button is pressed it opens the user form from the excel document and halts the other code until the user form is closed. Is there a way to only have the User Form open when it.
I have tried
Application.EnableEvents = False
However this just returns a method or data member not found (so I assume that this has to be run excel to excel?)
Sorry if this question has already been answered, I could not find anything that addressed this issue. Also sorry if this has a really simple solution, this is for a school project and this is my first time using VBA
Edit:
I realized that doing the following might work
exWb.Application.EnableEvents = False
However because I need to put this before the "Set" for it to stop the form from opening, it doesnt work (as the object is not set at the point the line is run).

You can disable Excel events with objExcel.EnableEvents = False before opening the workbook and reactivate them afterwards with objExcel.EnableEvents = True.
And as #Siddarth Rout told in comments, you can show your UserForm in Modeless mode with frmOpen.Show vbmodeless to avoid blocking other code execution. See MSDN remarks about this : https://msdn.microsoft.com/en-us/library/office/gg251819.aspx
So your code will look like this :
Private Sub cmdAutomatic_Click()
Dim objExcel As New Excel.Application
Dim exWb As Excel.Workbook
Dim selectID As String
objExcel.EnableEvents = False
Set exWb =objExcel.Workbooks.Open("C:\ Path")
exWb.Close
objExcel.EnableEvents = True
''Data is written into the document here
Set exWb = Nothing
Unload Me
End Sub

Related

Prevent MS-Word application from running auto macro when opening a Word document

I have a code in my excel file which opens a certain Word document to read data from, and that Word document also has an "Document_Open" event handler (Which Shows a UserForm every time I open that Word document).
My Problem is that every time I run my Excel code to open up that Word file due to that "Document_Open" event handler, control of the code stuck in Word environment.
My code so far:
Private Sub CommandButton18_Click()
Dim Word As New Word.Application
Dim MRpt As Word.Document
Word.Visible = True
Set MRpt = Documents.Open(Filename:="MyWordDocumentPath" &".docm")
'At This Point code will be stuck because my UserForm inside my Word
'document would show up and it prevents the code in Excel to continue)
End Sub
Based on the article in https://wordmvp.com/FAQs/InterDev/DisableAutoMacros.htm, you can disable/enable auto macro by using WordBasic.DisableAutoMacros:
Private Sub CommandButton18_Click()
Dim Word As New Word.Application
Dim MRpt As Word.Document
Word.Visible = True
Word.WordBasic.DisableAutoMacros 1 'Disable
Set MRpt = Documents.Open(Filename:="MyWordDocumentPath" &".docm")
'At This Point code will be stuck because my UserForm inside my Word
'document would show up and it prevents the code in Excel to continue)
Word.WordBasic.DisableAutoMacros 0 'Enable back
End Sub

Powerpoint VBA to switch back to powerpoint from Excel

I hope someone can help....
I have a powerpoint presentation, which has linked tables and graphs from an excel file. the updating of the slides are set to manual.
i have created a VBA code in Powerpoint which opens up the excel file. I am trying to update the links in the powerpoint through VBA instead of manually choosing each linked element and updating the values. while the first part of my VBA code works in opening up the excel file, the links are not being updated, which i think is down to not being back in the powerpoint to update the links, so I am trying to include in my VBA code lines which will go back to the powerpoint presentation, after which i assume the the line to update links will work (happy to be corrected). below is the code i have built so far....my comments are in bold ...
any suggestions?
FYI, I am using office 2007.
Thanks
Sub test()
Dim xlApp As Object
Dim xlWorkBook As Object
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = True
Set xlWorkBook = xlApp.Workbooks.Open("File location\filename.xlsm", True, False)
Set xlApp = Nothing
Set xlWorkBook = Nothing
Section above opens the excel file which contains the linked tables and charts
On Error Resume Next
With GetObject(, "PowerPoint.Application")
.ActivePresentation.SlideShowWindow.Activate
End With
Section above i was hoping would go back to the powerpoint after opening the excel file but it does not which is why i think the code below to update links is not working
ActivePresentation.UpdateLinks
End Sub
Start from something easier. This will allow you to activate the first existing PowerPoint application from Excel:
Option Explicit
Public Sub TestMe()
Dim ppt As New PowerPoint.Application
ppt.visible = msoTrue
ppt.Windows(1).Activate
End Sub
Then play a bit with it and fix it into your code.
#Vityata
Ok, i got it to work....original coding did the first part of opening the excel file, and to switch back to powerpoint (and i think this will only work if there is only 1 presentation open i added the following code...
AppActivate "Microsoft PowerPoint"
so my complete code looks like:
Sub test()
Dim xlApp As Object
Dim xlWorkBook As Object
Set xlApp = CreateObject("Excel.Application")
xlApp.Visible = True
Set xlWorkBook = xlApp.Workbooks.Open("file path\file name.xlsm", True, False)
Set xlApp = Nothing
Set xlWorkBook = Nothing
AppActivate "Microsoft PowerPoint"
End Sub
now to get manual links to update as part of the vba code...
If you capture the file that your macro is in. This is just a string of your path and filename
'This is the macro file
MacroFile = ActivePresentation.FullName
Then you can use that variable to activate just that specific PowerPoint presentation.
Use Presentations(MacroFile).Activate
or Presentations(MacroFile).Updatelinks
It's best not to use ActivePresentation when moving between applications.

VB.net manage opened excel file on the fly

In my current project, i need to modify an excel file that is already opened. That mean, i need to see the change in the excel file whenever i modify it.
Since opened file is locked and vb cannot access that file, my solution is to open another excel file, modify its content and then copy to the original file using excel vba, as excel vba can be used to copy data between opening sheets.
Here is the vb code in my other excel file (called TTHT.xlsm):
Private Sub Worksheet_CHANGE(ByVal Target As Range)
Application.ScreenUpdating = False
If Sheet1.[B5].Value = "#" Then
Application.DisplayAlerts = False
With Workbooks.Open(ThisWorkbook.Path & "\PCN.xlsm")
With ThisWorkbook.Sheets("TTHT").[B5]
.Parent.Range("B4").Copy
Sheets("PCN").[B4].PasteSpecial 7
End With
End With
Application.DisplayAlerts = True
End If
End Sub
Runs fine between my 2 opening excel file ( that TTHT one and PCN.xlsm ).
Now all I need to do, is to fill the data into TTHT, and put a "#" into B5 by my code. I think it will work, but it's not..
Private Sub btnUpdate_Click(sender As System.Object, e As System.EventArgs) Handles btnUpdate.Click
Dim oExcel As Object
Dim oBook As Object
Dim oSheet As Object
oExcel = CreateObject("Excel.Application")
oExcel.DisplayAlerts = False
oBook = oExcel.Workbooks.Open(TTHTPath)
oSheet = oBook.Worksheets("TTHT")
oSheet.Range("B4").Value = txtValue_Needed.text
oSheet.Range("B5").Value = "#"
oBook.Save()
'System.Diagnostics.Process.Start(DuongDanPhieuCongNghe)
oSheet = Nothing
oBook.Close()
oBook = Nothing
oExcel.Quit()
oExcel = Nothing
End Sub
Result is, if i open the PCN file and click button, it won't change. If I close the PCN and click button, it will change..
But i need to see the change on the fly, not by close and reopen each time i need to update.
Can someone shed me some light, as to how, or which function ... either vba or vb.net, should i use ?
If the file is already opened and has focus then you can try looking it up in the running objects table.
Dim ExcelApplication As Excel.Application
ExcelApplication = GetObject("C:\Folder\ExcelWorkbook.xls")
Then you can just make your modifications on the instance which you referenced while trying to avoid disrupting the user.
The getobject() function is great; here's a link.
https://msdn.microsoft.com/en-us/library/e9waz863(v=vs.71).aspx

AutoNew macro not working

I'm trying to get Word to open an Excel document whenever a document based on a specific template is created.
Here is my macro
Sub AutoNew()
Dim oExcel As Excel.Application
Dim oWB As Workbook
Set oExcel = New Excel.Application
Set oWB = oExcel.Workbooks.Open("E:\Letters.xlsx")
End Sub
When I double-click the template, it brings up a document based on the template just fine, but the macro doesn't run.
It shows up in the list of macros in the template, but attempting to run it doesn't do anything.
As has mentioned KazJaw, make app visible
Sub AutoNew()
Dim oExcel As Excel.Application
Dim oWB As Workbook
Set oExcel = New Excel.Application
Set oWB = oExcel.Workbooks.Open("E:\Letters.xlsx")
oExcel.Visible = true
End Sub
A disadvantage is, that excel application is launching as a new task (see tak manager) in case of another calling the macro - every document is opened in its own task.
The correct way is use API for launching a document in registered application, for example here: http://access.mvps.org/access/api/api0018.htm
Or one-row workaround, ugly, but works great:
Shell "cmd.exe /c start D:\a\test.xlsx"
Note that template with macro must have extension .xltm, not .xltx.

Is it possible to run a macro in Excel from external command?

Let's say I want to program a VBA code in an external program that opens an Excel file, runs a macro, saves (and say yes to any pop up windows), and close Excel. Is it possible to do so? If so, how would I go about implementing it?
You can launch Excel, open a workbook and then manipulate the workbook from a VBScript file.
Copy the code below into Notepad.
Update the 'MyWorkbook.xls' and 'Sheet1' parameters.
Save it with a vbs extension and run it.
Option Explicit
On Error Resume Next
ExcelMacroExample
Sub ExcelMacroExample()
Dim xlApp
Dim xlBook
Set xlApp = CreateObject("Excel.Application")
Set xlBook = xlApp.Workbooks.Open("C:\MyWorkbook.xls")
xlBook.Sheets("Sheet1").Cells(1, 1).Value = "My text"
xlBook.Sheets("Sheet1").Cells(1, 1).Font.Bold = TRUE
xlBook.Sheets("Sheet1").Cells(1, 1).Interior.ColorIndex = 6
xlBook.Save
xlBook.Close
xlApp.Quit
Set xlBook = Nothing
Set xlApp = Nothing
End Sub
This code above launches Excel opens a workbook, enters a value in cell A1, makes it bold and changes the colour of the cell. The workbook is then saved and closed. Excel is then closed.
Depending on what you are trying to achieve you may also 'control' Excel via (OLE) Automation from another application such as Access or Word or from your own application written in another environment such as Visual Basic (6). It is also possible to achieve this via .Net using a language of your choice (although some are easier to implement than others).
Are you wanting to control Excel from an external application or simply trigger a VBA macro in an existing workbook from the outside?
Again, depending on your intention, the workbook could have an Auto Open macro which could be conditional run based on an external value (say an ini file or database value).
I can think of several ways to do this.
You can start excel by creating a file with NotePad or a similar text editor.
Here are some steps:
Launch NotePad
Add the following line of text. Replace test.xlsm with the name and path for your file:
start Excel.exe "C\test.xlsm"
Save the file as "Test.bat".
Run the batch file.
The batch file should launch Excel and then open your file. The code in your workbook should run
OR
Again, using Notepad.
Option Explicit
On Error Resume Next
ExcelMacroExample
Sub ExcelMacroExample()
Dim xlApp
Dim xlBook
Set xlApp = CreateObject("Excel.Application")
Set xlBook = xlApp.Workbooks.Open("C:\MyWorkbook.xls", 0, True)
xlApp.Run "MyMacro"
xlApp.Quit
Set xlBook = Nothing
Set xlApp = Nothing
End Sub
Or, this.
'Code should be placed in a .vbs file
Set objExcel = CreateObject("Excel.Application")
objExcel.Application.Run "'C:\Users\Ryan\Desktop\Sales.xlsm'!SalesModule.SalesTotal"
objExcel.DisplayAlerts = False
objExcel.Application.Quit
Set objExcel = Nothing
Now, this isn't 'an external command', but the Windows Task Scheduler will do a nice job of opening that file for you, and once it is opened, you can run a tiny script like the one you see below.
Private Sub Workbook_Open()
Call CommandButton1_Click
End Sub
https://www.sevenforums.com/tutorials/11949-elevated-program-shortcut-without-uac-prompt-create.html