Excel: pass workbook object from sub to userform - excel

I want to pass two objects (one open workbook and other a table) from sub procedure to userform. I have made both of them global before the sub.
When I write just the two public declarations before Sub (they are set inside Sub),works good within Sub but when the userform initializes, it throws the error "Object variable or with block variable not set"
Public N As Workbook
Public E As ListObject
Sub...
I tried to set these two objects before Sub, the Sub doesn't run, throws compile error, "Invalid outside procedure"
Public N As Workbook
Set N = Workbooks.Open(ThisWorkbook.Sheets("New").Range("A1").Text)
Public E As ListObject
Set E = N.Sheets(1).ListObjects(1)
Sub...
How to pass object variables from Sub procedures to Userforms? Currently the only solution I see is to set the objects in both the Sub procedure and the Userform.

Add a Sub to your UserForm to set your Workbook and ListObject objects.
Userform:
Private pWB As Workbook
Private pLO As ListObject
Public Sub SetObjects(ByVal wb As Workbook, ByVal lo As ListObject)
Set pWB = wb
Set pLO = lo
End Sub
In your calling code:
Sub CallingCode()
Dim UF As UserForm1 ' Don't use the global UserForm1 object
Set UF = New UserForm1
UF.SetObjects N, E
UF.Show
End Sub

Related

Worksheet_Change event for multiple external workbooks

I have a class module that acts as a Worksheet_Change event for an external workbook. I am reworking my project, and the current setup only allows for one external workbook sheet_change event. I would, however, like this event listen for changes on multiple workbooks.
The amount of workbooks is unknown until midway in the code, so I can't create a predetermined amount of classes for each workbook.
Module Functions:
Dim oWb2 As New UpdaterUnkowns
Public Function
'Code...
Set oWb2.Workbook = newfile
End Function
Class module UpdaterUnknowns:
Public WithEvents m_wb As Workbook
Public CellVal As String
Public Property Set Workbook(wb As Workbook)
Set m_wb = wb
End Property
Public Property Get Workbook() As Workbook
Set Workbook = m_wb
End Property
Public Sub m_wb_SheetChange(ByVal Sh As Object, ByVal Target As Range)
'Code...
End Sub
Set oWb2.Workbook = newfile sets the workbook for the class module. Could I pass multiple workbooks to the event?
To handle every open workbook, you could do something like this:
Dim UU_collection As Collection
sub mysub()
Set uu_collection = New Collection
Dim wb As Workbook
For Each wb In Application.Workbooks
Dim oWb2 As UpdaterUnknowns
Set oWb2 = New UpdaterUnknowns
Set oWb2.Workbook = wb
uu_collection.Add oWb2
Next wb
End Sub

Automatically run macro if the user inserted a new worksheet

I would like my macro to run automatically if it detects that the user inserted a new worksheet into the workbook (existing & new).
Sub macro_run()
Dim Newws As Worksheet
Dim wb As Excel.Workbook
Dim sample1 As Worksheet
With ThisWorkbook
Set sample1 = .Sheets("Template")
For Each wb In Application.Workbooks
If Newws = sample1 Then
Application.Run "PERSONAL.XLSB!Opennew"
End If
Next wb
End With
End Sub
As mentioned in the comments you need to handle WorkbookNewSheet at Application level.
'-- Create a new Class.
'-- Name it clsGlobalHandler.
'-- Following Code goes in that class
'/ Create a variable to hold Application Object
Public WithEvents xlApp As Application
'/ Handle NewSheet event. Invoked whenever a new sheet is added
Private Sub xlApp_WorkbookNewSheet(ByVal Wb As Workbook, ByVal Sh As Object)
MsgBox Sh.Name
End Sub
'-- Create a new module
'-- Following code goes there
Option Explicit
'/ A new instance for the Class that we created.
Dim oGh As New clsGlobalHandler
'/ To start tracking sheet additions call this method first. Most likely in WorkBook_Open
'/ Once called any new sheet across the app insatnce will be intercepted.
Sub SetGlobalHandler()
Set oGh.xlApp = Application
End Sub
'/ Call this to remove the global handler.
Sub ResetGlobalHandler()
Set oGh.xlApp = Nothing
End Sub

Assign workbook to variable

I want to set ActiveWorkbook to a variable When workbook opens simultaneously ActiveWorkbook assign to a variable and that variable i can use in whole VBA excel project.
I tried to assigned in ThisWorkbook excel object on Workbook_open() function but it does not work.I provide that code below.
Private Sub Workbook_Open()
On Error Resume Next
Set WRBK = ActiveWorkbook
#If Mac Then
#Else
'unprotectVBProjProp
UnlockVBA ' Sujith ID: 12482
AddReferences ' Sujith ID: 12482
' protectVBProjProp
#End If
'MsgBox "xla Workbook opened"
Set eventInstance = New bwEvents
End Sub
So how can i set activeworkbook to a variable??
I am not so sure what are all the commands in the middle, like #If Mac Then , and UnlockVBA.
If you want to set the ActiveWorkbook to object WRBK, you will need to define WRBK in a regulare module as Public, and then use something like the code below:
Code in ThisWorkbook Module
Private Sub Workbook_Open()
Set WRBK = ActiveWorkbook
TestWorkbookName ' call sub <-- this is just to test the the workbook was assigned correctly
End Sub
Code in Regular Module
Option Explicit
Public WRBK As Workbook
Sub TestWorkbookName()
MsgBox WRBK.Name
End Sub

Excel VBA: Sub routine or function to handle hyperlink clicks

There's quite a bit of info about this to be found, but I haven't been able to get it to work for myself.
What I need to do is to have a global sub routine that catches hyperlink clicks for the whole document, not just the active sheet. Why? Because my workbook will have several links in several sheets, which are all "identical" except for their location (and contents of adjoining cells etc.).
This is easy to do with buttons - just connect all of them to the same macro - but I'm having problems doing the same with links.
This works, for one specific sheet:
In the Microsoft Excel Objects -> The worksheet in question:
Private Sub Worksheet_FollowHyperlink(ByVal Target As Hyperlink)
MsgBox "Link i Arket! " & Target.Range.Address
End Sub
When I click the link on the sheet in question, the VBA sub routine for the sheet catches the click and handles it.
The below code, I thought, "should" work for the whole document. That is, catch hyperlink clicks from any sheet in the worksbook. It does not (that is, nothing happens):
Sub Workbook_SheetFollowHyperlink(ByVal Sh As Object, ByVal Target As Hyperlink)
MsgBox "All sheets!"
End Sub
The links, in Excel, when hovering shows:
file://path/to/workbook.xlsm - click once to follow blablabla
What am I missing here?
You can reuse the same code for all worksheets by creating a class with a WithEvents worksheet object and storing the classes in a public collection.
Module1
Public objCollection As Collection
'Call on Workbook_Open
Sub CreateClasses()
Dim ws As Worksheet
Dim HyperlinksClass As cHyperlinks
'Create A New Instance Of The Collection
Set objCollection = New Collection
'Loop All Worksheets
For Each ws In Worksheets
'Create A New Class For This Worksheet
Set HyperlinksClass = New cHyperlinks
'Add The Worksheet To The Class
Set HyperlinksClass.obj = ws
'Add The Class To The Collection
objCollection.Add HyperlinksClass
Next ws
End Sub
Create a class called cHyperlinks
Private WithEvents pWS As Worksheet
Private Sub pWS_FollowHyperlink(ByVal Target As Hyperlink)
'Code to handle hyperlinks here
End Sub
Property Set obj(ByVal objWS As Worksheet)
Set pWS = objWS
End Property

Referring to subform record in access

I have the following form, with three subforms:
The button on the top right opens a userform in excel. I would like that userform to already have some of the selected values from these subforms. However, I am unable to refer to the records in the subforms in my VBA code. I've been successful in transferring the values from the main form, such as name etc. but not the ones from the subform. Code in access:
Option Compare Database
Private Sub Toggle159_Click()
Dim abc As String
abc = Me.CompanyName
Dim xlApp As Object 'Excel.Application, xlWB As Excel.Workbook
Dim xlWB As Object
Set xlApp = CreateObject("Excel.Application")
Set xlWB = xlApp.Workbooks.Open("C:\NA\eb\quotegenv2.xlsm") ' specify file
xlApp.Visible = True
xlApp.Run "Module3.showFormWithValues", abc
End Sub
In the above code, CompanyName is a control on the mainform. This code runs fine but I've tried to refer to items in the subform using 'me.subformname.form.controlname' but the control name does not appear in the suggestions.
Code in excel for the module:
' placed in code Module3
Sub showFormWithValues(txt1 As String)
With UserForm1
.ClientName.Text = txt1
End With
UserForm1.Show
End Sub
Any help is appreciated.
You have tried to set ClientName before the form is open.
Use a global variable at the top of module 3 to share the data between showFormWithValues and the form.
At the top of Module3 before the first procedure as a public variable as the example below shows: -
Option Explicit
Public StrCN As String
Sub showFormWithValues(txt1 As String)
...
End Eub
In UserForm1 add (or update if it already exists) the following: -
Private Sub UserForm_Activate()
Me.ClientName.Text = Module3.StrCN
End Sub

Resources