OnOpenExcelWorksheet Event To Trigger When Worksheet Opens? - events

How can I run code when a Worksheet opens? (The code that I want to run is contained in the opening worksheet)

You can put certain code in the Worksheet_Activate() function which will run when the sheet is selected. Additionally, use the Worksheet_Deactivate() to run code when you leave the wokrsheet and go to another one. These functions go in the worksheet object code.
Private Sub Worksheet_Activate()
MsgBox ("Hi")
End Sub
Private Sub Worksheet_Deactivate()
MsgBox ("Bye")
End Sub

I'm not sure how to get code to run when a worksheet opens, but you can get it to run when a workbook opens.
In the VBA editor, open the Microsoft Excel Object called "ThisWorkbook." At the top of the editor window, you should see two drop-down boxes: (General) and (Declarations). Change the (General) combo box to be "Workbook."
This will give you method called Workbook_Open(). Code placed in this method will execute when you open the Excel Workbook.
Furthermore, you have more events at your disposable, available in the (Declarations) section when you have Workbook selected, such as SheetActivate and SheetChanged, among others. I haven't used those methods, but they may be something to try if you need events related to individual worksheets and not just the entire workbook.

One way I have found to autorun while opening with Worksheet code only -without Workbook code - is with the Calculate event triggered by i.e. a formula =Now().
This can be relevant if copying the sheet to a new workbook should be allowed and the VBA code to run there as well.

You can also use static variables to run code only once in the Worksheet.Activate function like this...
Private Sub Worksheet_Activate()
Static Loaded as Variant
If Loaded <> True then
MsgBox ("Hi")
Loaded = True
End If
End Sub

Related

Word VSTO before-BeforeSave event?

Word has several events to hook into, to control application behavior etc.
Some of these events are: Document.BeforeSave and Application.BeforeSave
As far as I know, they do the same thing - they allow you to perform actions before the new document is saved, or even cancel the save event entirely.
But in later versions of Word, there seems to be an event happening BEFORE the BeforeSave events.
It shows a "Save this file" dialog:
Once the user has chosen where to save, and click [Save], THEN is the BeforeSave event executed.
I need a way to intercept this dialog, to prevent the user from saving in certain situations.
While I can do that with the current BeforeSave event, it results in a very bad user experience, since the user first chooses where to save, only to then be told that the time spent doing that was for nothing since the document is not allowed to be saved at this time.
In earlier versions of Word this was not an issue, Word just showed the regular (simple) Save As dialog whenever the user wanted to save the new document.
Coding in VB, I've tried these two ways to handle the BeforeSave Events at Document-level and Application-level. Both fire too late.
(C# code is also welcome, it's easily translated to VB in this context.)
' --- Handle BeforeSave at Document-level
Dim vstoDoc As Document = Globals.Factory.GetVstoObject(Me.Application.ActiveDocument)
AddHandler vstoDoc.BeforeSave, AddressOf clsWord.ThisDocument_BeforeSave
Public Shared Sub ThisDocument_BeforeSave(sender As Object, e As SaveEventArgs)
' Do stuff...
End Sub
' --- Handle BeforeSave at Application-level
Private Sub HandleDocumentBeforeSaveEvent(document As Word.Document, ByRef SaveAsUI As Boolean, ByRef Cancel As Boolean) Handles _wordApplication.DocumentBeforeSave
' Do stuff...
End Sub
How do I intercept the new dialog?
Alternatively, is there another way to prevent the user from saving the document (like setting a document property or something)?
I found a way.
First part is to expand the ribbon markup to include a <commands> node above the <ribbon> element (if any).
<commands>
<command idMso="FileSave" getEnabled="FileSave_GetEnabled"/>
<command idMso="FileSaveAs" getEnabled="FileSaveAs_GetEnabled"/>
</commands>
Then add callback methods to the ribbon code file:
Public Function FileSave_GetEnabled(ribControl As Office.IRibbonControl) As Boolean
' Simple test to toggle enabled/disabled easily
' - requires ribbon invalidation for changes to take effect though
Return My.Computer.Keyboard.CapsLock
End Function
Public Function FileSaveAs_GetEnabled(ribControl As Office.IRibbonControl) As Boolean
Return FileSave_GetEnabled(ribControl)
End Function
Finally you need to handle the BeforeSave event:
Private Sub HandleDocumentBeforeSaveEvent(Doc As Word.Document, ByRef SaveAsUI As Boolean, ByRef Cancel As Boolean) Handles _wdApp.DocumentBeforeSave
If MessageBox.Show("Do you REALLY want to save the document?", "BeforeSave", MessageBoxButtons.YesNo) = DialogResult.No Then
Cancel = True
Exit Sub
End If
End Sub
This allows you to disable the "Save"-icon in the top of the ribbon, Ctrl+S and the "Save" option in the File menu.
It does not disable the "Save as" option in the file menu, but whenever a user tries to save from there, the BeforeSave event is executed, allowing you to take action there.
All in all, a better solution than previously achieved!

VB6 Custom OCX integrating with another OCX Event/Method

I have created OCX in Vb6 which contains only Listview control(added from MSCOMCTL.ocx) and coded "drag and drop" functionality and currently I want to implement the OCX in another application but I'm not sure how to handle the event.
Listview has predefined Event/Method/Property, when I create my OCX the predified Lisview events are not loaded. example Listview1.Listitem
public sub Listviewocx()
eventvar1 = Data.Files.Count
For intCOunter = 1 To eventvar1
strpath = Data.Files(intCOunter)
msgbox strpath
next
end with
End sub
Thanks
Thiru
When you create ActiveX controls, you don't automatically expose the events, methods and properties of the constituent controls (in your case, the "constituent control" is the ListView). If, for example, you want a user of your control to have access to your ListView's click event, you have to raise the event again in the click event handler. Like this:
Sub ListView1_Click()
RaiseEvent "MyListViewClick"
End Sub
Then, in your application that uses your control:
Sub Listviewocx_MyListViewClick()
'Handle the event here
End Sub
You have to do similar things with properties and methods of your constituent controls.
For more information, read this and the related doc about ActiveX controls.

unable to save changes in our web application when running VB test script using testcomplete 11.0

I have Recorded a VB test script in TestComplete 11.0 and did some changes in our web application. when i was running the recorded test script, i didnt get any errors in log file which was generated by TestComplete but changes are not reflecting in our application.
Here is the VB Test Script:
Sub Test1
Dim browser
Dim page
Dim form
Dim textbox
Dim table
TestedApps.XXXcm.Run
Call Browsers.Item(btIExplorer).Navigate("http://localhost/XXXcm/connect.asp")
Set browser = Aliases.browser
Set page = browser.pageXXXConfigurationManager
Set form = page.formConnectform
Set textbox = form.textboxUsername
Call textbox.Drag(89, 12, -244, 6)
Call textbox.SetText("admin")
Call textbox.Keys("[Tab]")
Set table = form.tableYYYYtable
Call table.passwordboxPwd.SetText("XXXX")
table.submitbuttonLogin.ClickButton
page.Wait
Set page = browser.pageXXXConfigurationManagerField
Set textbox = page.tableDbfieldtable.cellColrubrik.textboxShortname
Call textbox.Click(85, 12)
Call page.Keys(" ")
Call textbox.SetText("Mobileno")
delay(5000)
page.buttonSave.ClickButton
page.Wait
End Sub
Could you please suggest me on this.
Thanks and Regards,
Sailaja
Try replacing SetText with Keys. SetText sets the text programmatically and may not trigger some keyboard events that you application may be listening to. Keys simulates actual typing on a keyboard.
To always record tests using Keys, go to Tools > Options > Engines > Recording and change the Record text input... option to Keys.

Visual Basic: Can not access TextBox attribiutes

Sorry. i am officially new in Visual Basic.
I have created a TextBox in my form. In "View Code" i want to access the Text attribute
(I mean TextBox.Text)
,but the object only gives me these 4: Count,Item,LBound,UBound
Maybe you're changing the Index property instead of the TabIndex property so that it would become a control array thus UBound, LBound, Count and Item properties are present.
And i suspect you are using Visual Basic 6 instead of VB.Net.
See link here the VB6 has Index property that is for Control Array.
My guess, without seeing your code is that your syntax is somehow interacting with an array, try this code:
Public Class Form1
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
Me.TextBox1.Text = "Hello World"
End Sub
End Class
Note: The above code represents the default names for a Form, a new TextBox dragged and dropped onto the designer inside of the form's Load event handler.
Are you possibly copying and pasting a textbox rather than double clicking the object in the toolbox. If you look in the name of the object in the properties window you would see txtName(0)

Word VBA Application Event fires more times when more documents opened

I have the following problem. I wrote simple macro which shows MsgBox before print dialog. Here is source:
Public WithEvents App As Application
Private Sub App_DocumentBeforePrint(ByVal Doc As Document, Cancel As Boolean)
MsgBox "aaaaa"
End Sub
Private Sub Document_New()
Set App = Application
End Sub
When I open one document from template with this macro, everything is OK. But I have a problem when I open two documents from this template at same time. When I click to print button, MsgBox shown up twice. Any ideas?
Edit:
When I create document from this template and create another new document, which isnt't based on this template (both of this documents are opened at the same time) and I print from that new empty document, MsgBox shown up. This is also wrong right?
You have created application-level events that fire every time any document is being printed. They are triggered once for every document that has this code in it, so every time you print a document you will get the msgbox once for every open document that has the code in it, whether or not the document that's printing has the code in it.
So, the behaviors aren't wrong, although clearly they are not what you want.
You should put the Before_Print event in the ThisDocument module of your template. That way the event will only happen once, and only when the document being printed has the code in it.
You could put a check in your App_DocumentBeforePrint sub to check whether the instance of the application object which is firing the event is the instance that contains the active document:
If Me <> ActiveDocument Then Exit Sub

Resources