Prevent VBA code from other workbook working with objects - vba

I need to disable a control (list box in this case), so user cannot get data from other departments. I do have a macro that can enable/disable it, and ask for password.
What I need is to prevent semidecent user to write a macro for enabling this list box in another workbook and unlocking it this way. It is possible in some way prevent VBA code from other modules to work with this control? So only code written in that one sheet can enable or disable it.
Thank you

What you can do is lock your VBA project and change your "subs" into "function", this way, a more advanced user have no access to the macro you've written without unlocking the project.
(Functions are not visible from the "assign a macro" button in the developer ribbon where Subs are)

I tried UserInterFaceOnly - and I'm not sure at this moment what it is supposed to do but it is not doing what I wanted
To be more clear, I have 2 list boxes and several comboboxes on Sheet1. When I'm sending file to users, I want to lock ListBoxes, or rather .enabled = False
What I'm trying to do is to prevent other user to write in some other workbook
Workbooks("opexRequest").Sheets("Report").ListBoxes("lstDepartment").Enabled = True
this line woudl enable the list box, and user can change values, and macro will genarate new SQL string for Departments user is not supposed to have access to. I need to have comboboxes enabled, so user can view different dates, and versions of plan for his department.
By accident I found a way I guess.
Within Sheet1 I have this code
Sub lstDepartment_change()
'checks first if lock checkbox is true/false, clears selection and disables listbox, _
if checkbox is locked and yet listbox is enabled and allows change
If Me.chkLock = True Then
Me.ListBoxes("lstDepartment").Enabled = False
Me.ListBoxes("lstdirector").Enabled = False
Call clearlistbox
End
ElseIf Me.chkLock = False Then
Call ControlsM.directorpopulation
End If
End Sub
Sub lstDirector_change()
'checks first if lock checkbox is true/false, clears selection and disables listbox, _
if checkbox is locked and yet listbox is enabled and allows change
If Me.chkLock = True Then
Me.ListBoxes("lstDepartment").Enabled = False
Me.ListBoxes("lstdirector").Enabled = False
Call clearlistbox
End
ElseIf Me.chkLock = False Then
End If
End Sub
Private Sub chkLock_Click()
'locking/unlocking with password inbox call
If Me.chkLock.Value = True Then
Me.ListBoxes("lstDepartment").Enabled = False
Me.ListBoxes("lstDirector").Enabled = False
ElseIf Me.chkLock.Value = False Then
If PasswordInputBoxM.InputBoxPassword("Enter password", "Password Required") = "****" Then
Me.ListBoxes("lstDepartment").Enabled = True
Me.ListBoxes("lstDirector").Enabled = True
Else
Me.chkLock.Value = True
MsgBox "Wrong Password"
Exit Sub
End If
End If
End Sub
If someone tries to unlock just listbox, and tries to change value, it will check the checkbox value, and clears the selected list and locks the listbox
If someone tries to unlock listbox and uncheck lock checkbox, it will automatically ask for password
Problem is, that someone can change selected value from other workbook. I do not know how to handle that
Workbooks("opexRequest").Sheets("Report").ListBoxes("lstDepartment").Enabled = True 'handled
Workbooks("opexRequest").Sheets("Report").chkLock.value = False 'handled
Workbooks("opexRequest").Sheets("Report").ListBoxes("lstDepartment").Selected(1) = True 'do not know how to prevent this

Related

VBA code for unhiding a bookmarked text is not working

I've created an ActiveX dropdown list and each option is linked to a bookmark for the text. Under the ActiveX controls there are the bookmarks (R1 andR2), hidden.
When I hit the btnselect button, all the other bookmarks, except the selected one, get deleted and the selected one becomes visible.
In the bookmark R2
I have a MacroButton for showing/hiding another text (CollapseMentiuniReclamant). When clicking the button it runs either Expand1 sub or Collapse1 sub, but the bookmark CollapseMentiuniReclamant doesn't show up.
I've simplified the document and codes as much as possible. Link to the document - https://wetransfer.com/downloads/1caea3c5d3b05e226e8b8f6a29760ad220190522071742/15db59.
The vba code is:
Private Sub btnselect_Click()
If ComboBox1.Value = "1" Then
Bookmarks("R1").Range.Font.Hidden = False
Bookmarks("R2").Range.Font.Hidden = False
Bookmarks("R2").Range.Delete
End If
If ComboBox1.Value = "2" Then
Bookmarks("R1").Range.Font.Hidden = False
Bookmarks("R1").Range.Delete
Bookmarks("R2").Range.Font.Hidden = False
Bookmarks("CollapseMentiuniReclamant").Range.Font.Hidden = True
End If
End Sub
Sub Expand1()
ActiveDocument.AttachedTemplate.BuildingBlockEntries("Collapse1").Insert _
Where:=Selection.Range
Bookmarks("CollapseMentiuniReclamant").Range.Font.Hidden = False
End Sub
Sub Collapse1()
ActiveDocument.AttachedTemplate.BuildingBlockEntries("Expand1").Insert _
Where:=Selection.Range
Bookmarks("CollapseMentiuniReclamant").Range.Font.Hidden = True
End Sub
Update: I've simplified the last part of code and the problem still persists:
Sub Expand1()
Bookmarks("CollapseMentiuniReclamant").Range.Font.Hidden = False
End Sub
I've even removed the button entirely and ran the macro from View Macros Tab and it's not working.
Why doesn't CollapseMentiuniReclamant show up?
It's not showing up because what you're trying to hide/unhide isn't inside the bookmarked range. In any event, you should be inserting/deleting the content, not simply toggling it's hidden property. Making something hidden is no guarantee it won't be seen or printed (even if not seen), as those settings depend on how the end user has Word configured.

VBA How to programaticly select an item in a listbox without triggering the on click event

I am using Excel 2010, Windows 10, with VBA. I have a function which runs upon clicking an item in an ActiveX ListBox control. The issue is that if you click the list box I ask if they are sure if they want to change the selection. If you click "yes" I continue, but if you say "no" I set the selection back to what it previously was.
So the issue is that when I programmatically set the list box selection back to the previous selection my function will re-run the code that runs if a user clicks an item in the list box ...which is what I don't want.
Does anyone have a better way to stop a list box selection and change it back to the old one without causing the on list box selection event to trigger?
Function prototype for on click of the list box
lsQuestions_Click()
Code for setting the list box selection
'Prototype: setListBoxSelection(query As String, listBoxName As String) As Boolean
' Purpose: Set listbox selection based on text
Public Function setListBoxSelection(query As String, listBoxName As String) As Boolean
Dim lsBox As MSForms.listBox
Set lsBox = Workbooks(mainFile).Worksheets(entrySheet).OLEObjects(listBoxName).Object
Dim I As Integer
For I = 0 To lsBox.ListCount - 1
If lsBox.List(I) = query Then
lsBox.Selected(I) = True
setListBoxSelection = True
Exit Function
End If
Next I
setListBoxSelection = False
End Function
Please note that I think the line of code below is what is triggering my click event which is what I don't want.
lsBox.Selected(I) = True
The way I do this with my VB6 projects is to define a module-scope variable
Private blnChangingInCode As Boolean
Then, when I need to utilize it, I set it to true, call the even/sub, set it back to false.
blnChangingInCode = True
btnLogin_Click()
blnChangingInCode = False
Inside the affected subs/events I start with
If blnChangingInCode Then
Exit Sub ' or Exit Function
End if
This might not be elegant, but it works, and I don't need to do it very often.

Set a sub-form hidden field to visible, based on a check box status

C, Thank you for your input and encouragement! I have changed my form and script slightly, I am afraid I kept the if then statement as I am comfortable with the formatting. The script now works when the 'On Open'event runs.
Private Sub Form_Open(Cancel As Integer)
Me.ChkAlbumNotes.SetFocus
If Me.ChkAlbumNotes.Value = False Then
Me.lblAlbumNotes.Visible = False
Me.txtAlbumNotes.Visible = False
Me.btnAlbumNotes.Visible = True
Else
Me.lblAlbumNotes.Visible = True
Me.txtAlbumNotes.Visible = True
Me.btnAlbumNotes.Visible = False
End If
Me.TrackName.SetFocus
If Me.TrackName = " " Then
Me.btnAddRecord.SetFocus
Else
Me.btnNextRecord.SetFocus
End If
End Sub
This is fine when the form opens for the first time but I have a set of navigation buttons that are installed by the application as Macros. I cannot add my script to the On_Click event when the button is clicked, as On_Click is linked to the Macro. Is there a way to incorporate the script from the On_Load process to the pre-defined macro? Or can you suggest a neater way to achieve my requirements which are;
When the form opens,a check is made for the existence of a false value in the checkbox
if the check box is set to false, then the Notes Text Box and label are hidden and the notes button is visible.
If the check box has a true value, then the Notes text box and label are made visible and the button is hidden.
On completion of the test I check the field Track Name
if this is empty, I assume I am at the last record and give the Add New Record button the focus
If Track Name is not empty, then focus is set to Next Record button
when this button is clicked, the next record page opens and the process starts again.
Many Thanks
Mike
You should use the Form_Current event instead of Form_Open . This fires on starting the form (2 times) and everytime you move to another record.
Private Sub Form_Current()
Me.lblAlbumNotes.Visible = Me.ChkAlbumNotes.Value
Me.txtAlbumNotes.Visible = Me.ChkAlbumNotes.Value
Me.btnAlbumNotes.Visible = Not Me.ChkAlbumNotes.Value
If Me.TrackName = "" Then ' I suggest If Me.TrackName = " " being a typo and you want to check if empty ( that's why you should use vbNullString instead of "")
Me.btnAddRecord.SetFocus
Else
Me.btnNextRecord.SetFocus
End If
End Sub

Disable checkboxes when sheet opened in vba

I have 3 checkboxes. When a user opened my sheet, he/she must not check checkboxes. I want them to be disabled. How can I do that?
Not sure if you meant ActiveX or FormControl, so here you go
Code
Private Sub Worksheet_Activate()
Dim myActiveX As Object
Set myActiveX = Sheet1.OLEObjects("CheckBox1")
myActiveX.Object.Value = True
myActiveX.Object.Locked = False ' Make it False if you wish to enable it
myActiveX.Object.Enabled = False ' Another option to disable
Dim myFormControl As CheckBox
Set myFormControl = ActiveSheet.Shapes("Check Box 1").OLEFormat.Object
myFormControl.Value = True
myFormControl.Enabled = False ' Make it True if you wish to enable it
End Sub
Live GIF demo
You have to write some VBA code in order to do that.
Let's suppose that you have 3 CheckBoxes in your first sheet.
By holding the "Alt" key on your keyboard and the pressing one time the "F11" key, opens Microsoft Visual Basic. ( Alt + F11 )
At your left hand you can see the "VBAProject" tree.
Double click on the "ThisWorkbook" file and copy the following code in the window it will appear:
Private Sub Workbook_Open()
void = uncheckAllCheckboxes()
End Sub
Function uncheckAllCheckboxes()
ThisWorkbook.Worksheets(1).CheckBox1.Value = False
ThisWorkbook.Worksheets(1).CheckBox2.Value = False
ThisWorkbook.Worksheets(1).CheckBox3.Value = False
End Function
Save the excel file as "Excel 97-2003 Workbook" type (.xls)
Close your excel.
Open the file you have previously saved and everything will work fine.
;)
P.S.: It is important to enable macros from your excel settings

Compile error with If statement on radiobutton.value

I'm trying to perform an action 'if a radioboxed have been checked", but I'm getting an error:
Compile error: Method or data member not found.
I've created a userform with four radiobuttons (using Controls toolbox), and a commandbutton. The userform loads in an excelsheet (with the click of a separate button), and it is possible to check the radiobutton. if the radiobutton is checked and I click the command button I want some action to happen, but it wont compile my code.
Private Sub cmdCSV_Click()
Dim JurBen As Integer
With Thisworkbook
If .lblRKinst.Value = True Then
JurBen = 1
MsgBox "hurray"
ElseIf .lblRKkon.Value = True Then
JurBen = 2
ElseIf lblForinst = True Then
JurBen = 3
ElseIf lblForkon = True Then
JurBen = 4
Else: Exit Sub
MsgBox ("Choose an option")
End If
It seems to dislike the "value" statement, which works fine with checkboxes? I've tried with "enabled" and without anything. I seem to be the only person on the internet with this problem...
As I've used loads of time on this tiny issue, and seem to be stuck, any help would be greatly appreciated!
If the Radioboxes are on UserForm then if you want to check their value then 1. the UserForm must be loaded at that time and 2. you need to refer to the UserForm.
Example:
if UserForm1.OptionButton1.Value = true then
The radiobox (OptionButton1 in my example) is member of UserForm and not of ThisWorkbook.
As written by Matteo NNZ I was simply referencing the label and not the radiobutton next to it.
No problem what so ever, as the code above works fine.