Application.CommandBars("vbaPopup").ShowPopup ··· how can I add `Submenu` (Ron de Bruin)? - excel

I have Microsoft Office 365 2019.
First of all i want to tell how code works:
Insert Note.
Click on Cell who has inserted Note.
Press Ctrl+N
Then you will see "PopUp-Menu".
I have VBA code (to work put in ThisWorkbook):
Private Sub Workbook_Open()
Application.OnKey "^{n}", CodeName & ".ContextMenu"
End Sub
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Application.OnKey "^{n}"
End Sub
Private Sub ContextMenu()
If ActiveCell Is Nothing Then Exit Sub
If ActiveCell.Comment Is Nothing Then Exit Sub
On Error Resume Next 'Can be and without inadequate to, but then with brute force(cycle) CommandBars.
Dim cb As CommandBar
Set cb = Application.CommandBars("vbaPopup")
If cb Is Nothing Then CreateContextMenu
Application.CommandBars("vbaPopup").ShowPopup
End Sub
Private Sub CreateContextMenu()
Dim a1_icon, a1_file, a2, a3, i&, m$, p$, f$: m = CodeName & ".": p = Path & "\Image\"
a1_icon = Array(76, 72, 178, 53)
a1_file = Array("NoteZoom_200x110.jpg", "NoteZoom_600x400.jpg", "Full Screen.jpg", "NoteZoom_InputBox.jpg", "Copy Text.jpg")
a2 = Array("NoteZoom 200x110", "NoteZoom 600x400", "Note <Full Screen>", "NoteZoom InputBox", "Скопировать текст примечания")
a3 = Array("NoteZoom1", "NoteZoom2", "NoteZoom3", "NoteZoom_InputBox", "NoteTextToClipboard")
With Application.CommandBars.Add("vbaPopup", msoBarPopup, , True) 'You can also not do to make the context menu temporary.
For i = 0 To UBound(a1_file) 'Ubound(a1_ico)
With .Controls.Add
f = p & a1_file(i)
If Len(Dir(f)) Then
.Picture = LoadPicture(f)
Else
.FaceId = a1_icon(i) 'If the file is not found, the icon. But it's not necessary.
End If
.Caption = a2(i)
.OnAction = m & a3(i)
End With
Next
End With
End Sub
Private Sub NoteZoom1(): NoteChangeSize 200, 110: End Sub
Private Sub NoteZoom2(): NoteChangeSize 600, 400: End Sub
Private Sub NoteZoom3()
With ActiveWindow.VisibleRange
NoteChangeSize .Width, .Height, True
'With .Resize(.Rows.Count - 1, .Columns.Count - 1) 'Without check
' NoteChangeSize .Width, .Height, True
'End With
End With
End Sub
Private Sub NoteChangeSize(w!, h!, Optional scr As Boolean)
With ActiveCell.Comment.Shape
.Width = w: .Height = h
If scr Then .Top = 0: .Left = 0: .Visible = msoTrue
End With
End Sub
'To create a `Note` with `InputBox`.
Private Sub NoteZoom_InputBox()
'Ниже 2 строчки для проверки наличия `Примечания`.
If ActiveCell Is Nothing Then Exit Sub
If ActiveCell.Comment Is Nothing Then Exit Sub
Dim lH As Long 'height
Dim lW As Long 'width
lH = Application.InputBox("Choose the HEIGHT of the notes ")
lW = Application.InputBox("Choose the WIDTH of the notes ")
With ActiveCell.Comment
' .Text Text:="Note:" & Chr(10) & ""
.Shape.Height = lH
.Shape.Width = lW
End With
End Sub
Private Sub NoteTextToClipboard()
With New DataObject
.SetText ActiveCell.Comment.Text
.PutInClipboard
End With
End Sub
For more details you can download my Excel Workbook to see how it's implemented!
Also i find code on this site Ron de Bruin. I wish to add "Submenu" in my "Menu"! Wrote out only those codes which can help to create "Submenu". But how to combine I don't know!?
Dim MenuItem As CommandBarPopup
'Add PopUp menu
With Application.CommandBars.Add(Name:=Mname, Position:=msoBarPopup, _
MenuBar:=False, Temporary:=True)
'Add menu with two buttons
Set MenuItem = .Controls.Add(Type:=msoControlPopup)
With MenuItem
.Caption = "My Special Menu"
With .Controls.Add(Type:=msoControlButton)
.Caption = "Button 1 in menu"
.FaceId = 71
.OnAction = "'" & ThisWorkbook.Name & "'!" & "TestMacro"
End With
In the end I want to get this:

0Key finally i find some solution for this. Right now it's looks like this:
Looks cool right? Download full code link.

Related

UserForm Object with Methods in VBA

I need to create an Object representing a UserForm, with methods to add Controls, and a method to present the UserForm.
I'm having a hard time wrapping my head around object-oriented VBA, and the tutorials/answers/documentation aren't helping me.
Here's how I imagine the Object and an example of its methods.
Sub UI_Window(caption as String)
Dim Form As Object
' This is to stop screen flashing while creating form
Application.VBE.MainWindow.Visible = False
Set Form = ThisWorkbook.VBProject.VBComponents.Add(1)
With Form
.Properties("Caption") = caption
.Properties("Width") = 600
.Properties("Height") = 50
End With
return Form
Sub addButton(action as String, code as String)
Set NewButton = Form.designer.Controls.Add("Forms.commandbutton.1")
With NewButton
.Name = "cmd_1"
.Caption = action
.Accelerator = "M"
.Top = Form.Height
.Left = 50
.Width = 500
.Height = 100
.Font.Size = 14
.Font.Name = "Tahoma"
.BackStyle = fmBackStyleOpaque
End With
' Adjust height of Form to added content
With Form
.Properties("Height") = Form.Height + NewButton.Height + 50
End With
' Should loop through code argument, line-by-line
Form.codemodule.insertlines 8, "Private Sub cmd_1_Click()"
Form.codemodule.insertlines 9, "msgbox (""Button clicked!"")"
Form.codemodule.insertlines 10, "End Sub"
End Sub
Sub present()
'Show the form
VBA.UserForms.Add(Form.Name).Show
'Delete the form
ThisWorkbook.VBProject.VBComponents.Remove Form
End Sub
End Sub
And here's how it would be used
Sub SampleWindow()
Set Window = UI_Window "Window Title"
Window.addButton "Click me", "msgbox (""Button clicked!"")"
Window.present()
End Sub
Please, try this adapted way:
Copy the next code on top of module where the following code exists:
Public frm As Object 'to use it even after the UserForm has been created
'to avoid it deletion when tested the code
Copy the next code in the same standard module:
Sub CreateAFormWithAButton()
Const formName As String = "MyNewForm"
Const formCaption As String = "My Form"
removeForm formName 'remove the previously created form, if the case
UI_Window formCaption, formName 'create the new form
addButton frm, "myFirstButton", "Click Me" 'add a button
VBA.UserForms.Add(frm.Name).Show 'show the newly created form
End Sub
Function formExists(frmName As String) As Boolean
Dim fr As Variant
For Each fr In ThisWorkbook.VBProject.VBComponents
If fr.Type = vbext_ct_MSForm Then
If frmName = fr.Name Then
Set frm = fr
formExists = True: Exit Function
End If
End If
Next
End Function
Sub UI_Window(frmCaption As String, frmName As String)
Set frm = ThisWorkbook.VBProject.VBComponents.Add(vbext_ct_MSForm) '3
With frm
.Properties("Caption") = frmCaption
.Properties("Width") = 500
.Properties("Height") = 200
.Properties("Name") = frmName
End With
End Sub
Sub addButton(form As Object, btName As String, btCaption As String)
Dim NewButton As MSForms.CommandButton
If buttonExists(btName) Then MsgBox "A button named """ & btName & """ already exists...": Exit Sub
Set NewButton = form.Designer.Controls.Add("Forms.commandbutton.1")
With NewButton
.Name = btName
.caption = btCaption
.top = 0
.left = 50
.width = 100
.height = 40
.Font.size = 14
.Font.Name = "Tahoma"
End With
' Should loop through code argument, line-by-line
form.CodeModule.InsertLines 8, "Private Sub " & btName & "_Click()"
form.CodeModule.InsertLines 9, " msgbox (""Button clicked!"")"
form.CodeModule.InsertLines 10, "End Sub"
End Sub
Function buttonExists(btName As String) As Boolean
Dim ctrl As Variant
For Each ctrl In frm.Designer.Controls
If ctrl.Name = btName Then buttonExists = True: Exit Function
Next
End Function
Sub removeForm(frmName As String)
Dim i As Long, strName As String
If Not formExists(frmName) Then Exit Sub
strName = "TestName"
tryAgain:
On Error Resume Next
frm.Name = strName
If err.Number = 75 Then 'a previously used name...
err.Clear 'clear the error
strName = strName & i: i = i + 1 'increment the new string
frm.Name = strName: GoTo tryAgain 'test the new name again
End If
On Error GoTo 0
ThisWorkbook.VBProject.VBComponents.Remove frm
End Sub
If you will try running the code for the second time, you cannot create a button with the same name. The code check if the name exists and warn. It can be adapted to propose another name (adding an incremented number), but it needs also to set other positioning, making the code more complicated and this does not make the object of the question, I would say...
Please, run/test it and send some feedback.

Use VBA code for enabling checkboxes on multiple rows

enter image description hereI have a spreadsheet that has 3 checkbox options for each row, I have created a VBA to disable the other 2 checkboxes once a checkbox is created (so that only 1 checkbox can be checked), however my solution only works for one row and I need some help in rewriting this so that it will apply to all rows please. (I'm new to VBA).
The code I have used is this:
Private Sub CheckBox1_Click()
If CheckBox1.Value = True Then
CheckBox2.Value = False
CheckBox2.Enabled = False
CheckBox3.Value = False
CheckBox3.Enabled = False
Else
CheckBox2.Value = False
CheckBox2.Enabled = True
CheckBox3.Value = False
CheckBox3.Enabled = True
End If
End Sub
Private Sub CheckBox2_Click()
If CheckBox2.Value = True Then
CheckBox1.Value = False
CheckBox1.Enabled = False
CheckBox3.Value = False
CheckBox3.Enabled = False
Else
CheckBox1.Value = False
CheckBox1.Enabled = True
CheckBox3.Value = False
CheckBox3.Enabled = True
End If
End Sub
Private Sub CheckBox3_Click()
If CheckBox3.Value = True Then
CheckBox1.Value = False
CheckBox1.Enabled = False
CheckBox2.Value = False
CheckBox2.Enabled = False
Else
CheckBox1.Value = False
CheckBox1.Enabled = True
CheckBox2.Value = False
CheckBox2.Enabled = True
End If
End Sub
You should probably just use Radios it would be a lot simpler.
If you are intent on doing this you will need to delete all your boxes and then put this code in. It will create and name your boxes and assign them code on click.
Alright, This needs to go in your Sheet module:
Sub Worksheet_Activate()
'Change Module2 to whatever the module name you are using is.
Module2.ActivateCheckBoxes ActiveSheet
End Sub
This next stuff will go into the module you're referencing from the Worksheet Module.
Sub ActivateCheckBoxes(sht As Worksheet)
If sht.CheckBoxes.Count = 0 Then
CreateCheckBoxes sht
End If
Dim cb As CheckBox
For Each cb In sht.CheckBoxes
'You may be able to pass sht as an object, It was giving me grief though
cb.OnAction = "'Module2.CheckBoxClick """ & cb.name & """, """ & sht.name & """'"
Next cb
End Sub
Sub CreateCheckBoxes(sht As Worksheet)
Dim cell As Range
Dim chkbox As CheckBox
With sht
Dim i As Long
Dim prevrow As Long
prevrow = 0
For Each cell In .Range("B2:D5") 'Change this to whatever range you want.
If prevrow < cell.row Then
prevrow = cell.row
i = 0
End If
Set chkbox = .CheckBoxes.Add(cell.Left, cell.Top, 30, 6)
With chkbox
.name = "CheckBox" & i & "_" & cell.row
.Caption = ""
End With
i = i + 1
Next cell
End With
End Sub
Sub CheckBoxClick(chkname As String, sht As String)
Dim cb As CheckBox
With Worksheets(sht)
For Each cb In .CheckBoxes
If Split(cb.name, "_")(1) Like Split(chkname, "_")(1) And Not cb.name Like chkname Then
cb.Value = -4146
End If
Next cb
End With
End Sub
You do not say anything about your sheet check boxes type... Please, test the next solution. It will be able to deal with both sheet check boxes type:
Copy this two Subs in a standard module:
Public Sub CheckUnCheckRow(Optional strName As String)
Dim sh As Worksheet, s As CheckBox, chK As OLEObject ' MSForms.CheckBox
Set sh = ActiveSheet
If strName <> "" Then
Set chK = sh.OLEObjects(strName) '.OLEFormat.Object
solveCheckRow chK.Object.Value, sh, Nothing, chK
Else
Set s = sh.CheckBoxes(Application.Caller)
solveCheckRow s.Value, sh, s
End If
End Sub
Sub solveCheckRow(boolVal As Long, sh As Worksheet, chF As CheckBox, Optional chK As OLEObject)
Dim s As CheckBox, oObj As OLEObject, iCount As Long
If Not chF Is Nothing Then
For Each s In sh.CheckBoxes
If chF.TopLeftCell.Address <> s.TopLeftCell.Address Then
If s.TopLeftCell.Row = chF.TopLeftCell.Row Then
s.Value = IIf(boolVal = -4146, 1, -4146): iCount = iCount + 1
If iCount = 2 Then Exit Sub
End If
End If
Next
ElseIf Not chK Is Nothing Then
For Each oObj In sh.OLEObjects
If oObj.TopLeftCell.Address <> chK.TopLeftCell.Address Then
If oObj.TopLeftCell.Row = chK.TopLeftCell.Row Then
boolStopEvents = True
oObj.Object.Value = IIf(boolVal = 0, True, False): iCount = iCount + 1
boolStopEvents = False
If iCount = 2 Then Exit Sub
End If
End If
Next
End If
End Sub
For case of Form check boxes type:
a). Manually assign the first sub to all your Form Type check boxes (right click - Assign Macro, choose CheckUnCheckRow and press OK).
b). Automatically assign the macro:
Dim sh As Worksheet, s As CheckBox
Set sh = ActiveSheet ' use here your sheet keeping the check boxes
For Each s In sh.CheckBoxes
s.OnAction = "'" & ThisWorkbook.Name & "'!CheckUnCheckRow"
Next
End Sub
If your check boxes have already assigned a macro, adapt CheckUnCheckRow, in Form check boxes section, to also call that macro...
For case of ActiveX check boxes:
a). Create a Public variable on top of a standard module (in the declarations area):
Public boolStopEvents
b). Manually adapt all your ActiveX check boxes Click or Change event, like in the next example:
Private Sub CheckBox1_Click()
If Not boolStopEvents Then CheckUnCheckRow "CheckBox1"
End Sub
Private Sub CheckBox2_Click()
If Not boolStopEvents Then CheckUnCheckRow "CheckBox2"
End Sub
Private Sub CheckBox3_Click()
If Not boolStopEvents Then CheckUnCheckRow "CheckBox3"
End Sub
and so on...
c). Or do all that with a click, using the next piece of code:
Sub createEventsAllActiveXCB()
Dim sh As Worksheet, oObj As OLEObject, strCode As String, ButName As String
Set sh = ActiveSheet 'use here your sheet keeping ActveX check boxes
For Each oObj In sh.OLEObjects
If TypeName(oObj.Object) = "CheckBox" Then
ButName = oObj.Name
strCode = "Private Sub " & ButName & "_Click()" & vbCrLf & _
" If Not boolStopEvents Then CheckUnCheckRow """ & ButName & """" & vbCrLf & _
"End Sub"
addClickEventsActiveXChkB sh, strCode
End If
Next
End Sub
Anyhow, the code cam be simplified in order to deal with only a type of such check boxes. If you intend to use it and looks too bushy, I can adapt it only for the type you like. Like it is, the code deals with both check box types, if both exist on the sheet...
Save the workbook and start playing with the check boxes. But, when you talk about check boxes on a row, all tree of them must have the same TopLeftCell.Row...

Load image, and populate listbox by selecting dependent combobox

I'm trying to load img from folder path, and populate listbox by dependent combobox selection
so far I have this code attached below
Private Sub ComboBox3_Change()
Private Sub UserForm_Initialize()
ComboBox1.RowSource = "EngType"
ComboBox2.Value = "Please Select Engine Type"
End Sub
Private Sub ComboBox1_Change()
If ComboBox1.Text = "IF" Then
ComboBox2.Value = ""
ComboBox2.RowSource = "IF"
ElseIf ComboBox1.Text = "GMT" Then
ComboBox2.RowSource = "GMT"
End If
End Sub
Private Sub ComboBox2_Change()
Dim dtRange As Range, itm As Variant, i As Long, ImgAdrs As String
ImgFile = ThisWorkbook.Path & "\IMG\IF"
If ComboBox2.Value <> "Please Select Engine Type" Then
UserForm.Image1.Picture = LoadPicture(ImgFile & ComboBox2.Text & ".jpg")
Else
UserForm.Image1.Picture = LoadPicture(ThisWorkbook.Path & "\IMG\IF\W_logo_color_pos_RGB.jpg")
End If
With Sheets("UserForm")
If ComboBox1.Text = "IF" Then
Set dtRange = .Range("J2:J2000").Find(What:=Me.ComboBox2.Value)
If Not dtRange Is Nothing Then
For Each itm In .Range("K2:N2000")
ListBox1.AddItem itm
Next
End If
ElseIf ComboBox1.Text = "GMT" Then
Set dtRange = .Range("E2:E2000").Find(What:=Me.ComboBox2.Value)
If Not dtRange Is Nothing Then
For Each itm In .Range("F2:H2000")
ListBox1.AddItem itm
Next
End If
End If
End With
End Sub
it populates a listbox but all the list populates in first column and I'm kept getting error from img when I select second combobox
any idea?

Commandbar Code Works In Standard Module But Not In "ThisWorkbook" Module

I have a procedure that creates a CommandBar with 5 controls. The first control button works perfectly, but the macros called by the 3 sub-buttons of the second control button show the following error on button click: Cannot run the macro Heavy MX C D check status 2018 Rev 28 2019 Rev 1 January 2019 Working.xlsb'!SubName'. The macro may not be available in this workbook or all macros may be disabled. I have ensured that all macros are Enabled so that isn't the issue.
That Being Said, My Controls/Buttons are set up as follows:
First control: A button, called Get Transactions. This control works perfectly in the ThisWorkbook module and the standard module.
Second Control: A popup called Sheet Actions that houses three subcontrol buttons. This is where the issue lies. I have subprocedures which are called by the OnAction property when the any of the 3 sub-buttons are clicked, but I am receiving the aforementioned error. Each sub is called by each of the 3 buttons are placed directly below the CreateToolbar sub in the ThisWorkbook Module. I have already tried the following formats for OnAction with no success:
OnAction = "SubName"
OnAction = "'SubName'"
OnAction = ' & ThisWorkbook.Name & "'!SubName"
Pictures of Controls:
Below is my code:
Private Sub CreateToolbar()
'called from Workbook Open event procedure
Dim Cbar As CommandBar
Dim CbarControl As CommandBarControl
Dim CbarControlSub1 As CommandBarControl
Dim CbarControlSub2 As CommandBarControl
Dim CbarControlSub3 As CommandBarControl
'Get rid of any existing toolbar
Application.CommandBars(sToolbarName).Delete
'*************************************************************
'This works as inteneded
Set Cbar = Application.CommandBars.Add(Name:=sToolbarName)
'Create the new toolbar
With Cbar
'Add a toolbar command button
With .Controls.Add(Type:=msoControlButton)
.OnAction = "'" & ThisWorkbook.Name & "'!GetTransactions"
.ShortcutText = "Ctrl+Shift+G"
.Caption = "Get Transactions"
.Style = msoButtonCaption
.TooltipText = "Click to Import and Categorize transactions."
End With
.Visible = True
.Position = msoBarTop
End With
Application.MacroOptions Macro:="GetTransactions", _
HasShortcutKey:=True, _
ShortcutKey:="G"
Application.OnKey "^+g", "GetTransactions"
'*************************************************************
'*************************************************************
'This is where I am having issues
Set CbarControl = Cbar.Controls.Add(Type:=msoControlPopup)
CbarControl.Caption = "Sheet Actions"
Set CbarControlSub1 = CbarControl.Controls.Add(Type:=msoControlButton)
With CbarControlSub1
.Style = msoButtonIconAndCaption
.Caption = "Filter For New Transations"
.OnAction = "FilterForNewTrans"
.BeginGroup = True
End With
Set CbarControlSub2 = CbarControl.Controls.Add(Type:=msoControlButton)
With CbarControlSub2
.Style = msoButtonIconAndCaption
.Caption = "Clear Transaction Filter"
.OnAction = "ClearFilter"
.BeginGroup = True
End With
Set CbarControlSub3 = CbarControl.Controls.Add(Type:=msoControlButton)
With CbarControlSub3
.Style = msoButtonIconAndCaption
.Caption = "Clear Row Fill Color"
.OnAction = "ClearFillColor"
.BeginGroup = True
End With
'*************************************************************
End Sub
Any ideas, suggestions, or answers would be greatly appreciated.
I was never able to get the code to run in the ThisWorkbook Module, however I did get it to work in a standard module. I pulled the CreateToolbar sub along with the sub procedures for the buttons into a standard module and left them as private. In the ThisWorkbook Module, which fires on Workbook_Open, I changed Call CreateToolbar to Application.Run "'" & ThisWorkbook.Name & "'!CreateToolbar" and it works as intended. For the Subs that are run on button click, I used Application.OnKey "somekeycombination", "SomeSubName".
The following is the final code for the CommandBar with additional buttons:
Private Sub CreateToolbar()
'called from Workbook Open event procedure
Dim Cbar As CommandBar 'ToolBar
Dim CbarControl_1 As CommandBarControl
Dim CbarControl_2 As CommandBarControl
Dim CbarControl_3 As CommandBarControl
Dim ControlSubA1 As CommandBarControl
Dim ControlSubA2 As CommandBarControl
Dim ControlSubB1 As CommandBarControl
Dim ControlSubB2 As CommandBarControl
Dim ControlSubB3 As CommandBarControl
Dim ControlSubB4 As CommandBarControl
Dim ControlSubB5 As CommandBarControl
'Get rid of any existing toolbar
On Error Resume Next
Application.CommandBars(ToolbarName).Delete
'**************************************
'Add the Toolbar
'**************************************
Set Cbar = Application.CommandBars.Add(Name:=ToolbarName)
With Cbar
.Visible = True
.Position = msoBarTop
End With
'**************************************
'********************************************************************
'Button1
'********************************************************************
Set CbarControl_1 = Cbar.Controls.Add(Type:=msoControlPopup)
CbarControl_1.Caption = "Get Transactions"
'**************************
'SubButton1: Ctrl+Shift+G
'**************************
Set ControlSubA1 = CbarControl_1.Controls.Add(Type:=msoControlButton)
With ControlSubA1
.Style = msoButtonIconAndCaption
.Caption = "Import/Categorize ALL RECENT transactions"
.OnAction = "GetCurrMonTransactions"
.ShortcutText = "Ctrl+Shift+G"
.BeginGroup = True
Application.OnKey "^+g", "GetCurrMonTransactions"
End With
'**************************
'SubButton2: Ctrl+Shift+P
'**************************
Set ControlSubA2 = CbarControl_1.Controls.Add(Type:=msoControlButton)
With ControlSubA2
.Style = msoButtonIconAndCaption
.Caption = "Import/Categorize PREVIOUS MONTH'S transactions"
.OnAction = "GetPrevMonthTransactions"
.ShortcutText = "Ctrl+Shift+P"
.BeginGroup = True
Application.OnKey "^+p", "GetPrevMonthTransactions"
End With
'********************************************************************
'********************************************************************
'********************************************************************
'Button 2: Ctrl+Shift+U
'********************************************************************
Set CbarControl_2 = Cbar.Controls.Add(Type:=msoControlButton)
With CbarControl_2
.OnAction = "'" & ThisWorkbook.Name & "'!UploadTransToSQL"
.Caption = "Save To SQL"
.ShortcutText = "Ctrl+Shift+U"
.Style = msoButtonCaption
.TooltipText = "Click to Export updated transactions to the SQL Server"
Application.OnKey "^+u", "UploadTransToSQL"
End With
'********************************************************************
'********************************************************************
'********************************************************************
'Button 3
'********************************************************************
Set CbarControl_3 = Cbar.Controls.Add(Type:=msoControlPopup)
CbarControl_3.Caption = "Sheet Actions"
'*************************
'SubButton1: Ctrl+Shift+F
'*************************
Set ControlSubB1 = CbarControl_3.Controls.Add(Type:=msoControlButton)
With ControlSubB1
.Style = msoButtonIconAndCaption
.Caption = "Filter For New Transations"
.OnAction = "FilterForNewTrans"
.ShortcutText = "Ctrl+Shift+F"
.BeginGroup = True
Application.OnKey "^+f", "FilterForNewTrans"
End With
'*************************
'SubButton2: Ctrl+Shift+O
'*************************
Set ControlSubB2 = CbarControl_3.Controls.Add(Type:=msoControlButton)
With ControlSubB2
.Style = msoButtonIconAndCaption
.Caption = "Filter for Old Updated Transactions"
.OnAction = "FilterForOldUpdates"
.ShortcutText = "Ctrl+Shift+O"
.BeginGroup = True
Application.OnKey "^+o", "FilterForOldUpdates"
End With
'***********************
'SubButton3: Ctrl+Alt+c
'***********************
Set ControlSubB3 = CbarControl_3.Controls.Add(Type:=msoControlButton)
With ControlSubB3
.Style = msoButtonIconAndCaption
.Caption = "Clear Transaction Filters"
.OnAction = "ClearFilter"
.ShortcutText = "Ctrl+Alt+c"
.BeginGroup = True
Application.OnKey "^%c", "ClearFilter"
End With
'************************
'SubButton4: Ctrl+Alt+r
'************************
Set ControlSubB4 = CbarControl_3.Controls.Add(Type:=msoControlButton)
With ControlSubB4
.Style = msoButtonIconAndCaption
.Caption = "Clear Row Fill Color"
.OnAction = "ClearFillColor"
.ShortcutText = "Ctrl+Alt+r"
.BeginGroup = True
Application.OnKey "^%r", "ClearFillColor"
End With
'************************
'SubButton5: Ctrl+Alt+a
'************************
Set ControlSubB5 = CbarControl_3.Controls.Add(Type:=msoControlButton)
With ControlSubB5
.Style = msoButtonIconAndCaption
.Caption = "Toggle formula Auto-Calculations"
.OnAction = "TurnOnAutoCalc"
.ShortcutText = "Ctrl+Alt+a"
.BeginGroup = True
Application.OnKey "^%a", "TurnOnAutoCalc"
End With
'********************************************************************
'********************************************************************
End Sub
And the code in the ThisWorkbook Module:
Private Sub Workbook_Open()
Application.Run "'" & ThisWorkbook.Name & "'!CreateToolbar"
End Sub
'When this workbook is the active workbook, the toolbar will be enabled and show up
Private Sub Workbook_Activate()
On Error Resume Next
With Application.CommandBars(ToolbarName)
.Enabled = True
.Visible = True
End With
End Sub
'When the user activates another workbook, this disables the command bar
Private Sub Workbook_Deactivate()
On Error Resume Next
With Application.CommandBars(ToolbarName)
.Enabled = False
.Visible = False
End With
End Sub

excel 2007 method oleobjects of object failed

I have an invoice set up with validation list on a separate worksheet listing all our parts we sell. I put combo boxes on the invoice and linked them to the validation list and included code so that when box is double clicked, it will start auto completing the box using the validation list when typed. I also included code so that when this invoice is closed at end of the day, and then reopened the next day, or when shortcut key is pressed, it will clear the contents and change the invoice number.
Sometimes I need to save a, invoice to add on or change later. So I copy that worksheet and rename it with customer name. This has worked fine for over a year. But last week, when I click on any cell on the copied worksheets, it has a runtime error 1004 Method "OLEObjects" of object"_Worksheet" failed. Then the combo boxes don't work. But it only does it on the copied worksheets. The original worksheet works fine. Any suggestions? Here is the code used:
'==========================
Private Sub Worksheet_BeforeDoubleClick(ByVal Target As Range, _
Cancel As Boolean)
Dim str As String
Dim cboTemp As OLEObject
Dim ws As Worksheet
Dim wsList As Worksheet
Set ws = ActiveSheet
Set wsList = Sheets("ValidationLists")
Cancel = True
Set cboTemp = ws.OLEObjects("Parts")
On Error Resume Nex
With cboTemp
'clear and hide the combo box
.ListFillRange = ""
.LinkedCell = ""
.Visible = False
End With
On Error GoTo errHandler
If Target.Validation.Type = 3 Then
'if the cell contains a data validation list
Application.EnableEvents = False
'get the data validation formula
str = Target.Validation.Formula1
str = Right(str, Len(str) - 1)
With cboTemp
'show the combobox with the list
.Visible = True
.Left = Target.Left
.Top = Target.Top
.Width = Target.Width + 5
.Height = Target.Height + 5
.ListFillRange = str
.LinkedCell = Target.Address
End With
cboTemp.Activate
End If
errHandler:
Application.EnableEvents = True
Exit Sub
End Sub
Private Sub Worksheet_Change(ByVal Target As Range)
End Sub
'=========================================
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Dim str As String
Dim cboTemp As OLEObject
Dim ws As Worksheet
Set ws = ActiveSheet
Application.EnableEvents = False
Application.ScreenUpdating = True
If Application.CutCopyMode Then
'allow copying and pasting on the worksheet
GoTo errHandler
End If
Set cboTemp = ws.OLEObjects("Parts")
On Error Resume Next
With cboTemp
.Top = 10
.Left = 10
.Width = 0
.ListFillRange = ""
.LinkedCell = ""
.Visible = False
.Value = ""
End With
errHandler:
Application.EnableEvents = True
Exit Sub
End Sub
'====================================
'Optional code to move to next cell if Tab or Enter are pressed
'from code by Ted Lanham
Private Sub Parts_KeyDown(ByVal _
KeyCode As MSForms.ReturnInteger, _
ByVal Shift As Integer)
Select Case KeyCode
Case 9 'Tab
ActiveCell.Offset(0, 1).Activate
Case 13 'Enter
ActiveCell.Offset(1, 0).Activate
Case Else
'do nothing
End Select
End Sub
Set cboTemp = ws.OLEObjects("Parts") is where the problem is. It appears twice and gets flagged on both of them.

Resources