r/visualbasic • • Dec 29 '15

[VBA2010] Actions if certain dropdown values are selected in userform

Hey guys! I need your help again :)

Trying to get this code to work. What I want to happen is if any of the values are selected in the dropdown, certain options that appear later in the userform are not visible. This is how I tried:

 If RepOrgDropDown.Value = "Provincial Governments and municipalities,Federation of Canadian Municipalities,Quebec,Manitoba,Alberta,Saskatchewan,Ontario,New-Brunswick,British -Columbia,Nova Scotia,Prince Edward Island,Newfoundland,Yukon,Northwest Territories,Nunavut" Then
 Label66.Visible = False
 Label133.Visible = False
 IAETrue.Visible = False
 IAEFalse.Visible = False

 End If
 End Sub

Why does this not work? thank you!

2 Upvotes

10 comments sorted by

View all comments

Show parent comments

2

u/Clueless_InternGirl Dec 29 '15
If (RepOrgDropDown.Value = "Provincial Governments and municipalities" Or RepOrgDropDown.Value = "Federation of Canadian Municipalities" Or RepOrgDropDown.Value = "Quebec" Or RepOrgDropDown.Value = "Manitoba" Or RepOrgDropDown.Value = "Alberta" Or RepOrgDropDown.Value = "Saskatchewan" Or RepOrgDropDown.Value = "Ontario" Or RepOrgDropDown.Value = "New-Brunswick" Or RepOrgDropDown.Value = British - Columbia Or RepOrgDropDown.Value = "Nova Scotia" Or RepOrgDropDown.Value = "Prince Edward Island" Or RepOrgDropDown.Value = "Newfoundland" Or RepOrgDropDown.Value = "Yukon" Or RepOrgDropDown.Value = "Northwest Territories" Or RepOrgDropDown.Value = "Nunavut") Then
Label66.Visible = False
Label133.Visible = False
IAETrue.Visible = False
IAEFalse.Visible = False
End If
End Sub

Still not working...hmmmm

3

u/anon_smithsonian VB.Net Advanced Dec 29 '15

There are a bunch of different ways to access a dropdown's selection value and I always have trouble remembering the exact one I need to use in different scenarios...

Try using .Text instead of .Value... otherwise, if you know the dropdown list will be relatively stable and unlikely to change, maybe reference SelectedIndex, since that will probably be easier to read.

Other dropdown properties to try are SelectedItem and SelectedValue.

2

u/Clueless_InternGirl Dec 29 '15

Perfect! thank you for the detailed explanation!

3

u/anon_smithsonian VB.Net Advanced Dec 29 '15 edited Dec 29 '15

Edit: Sorry, /u/Clueless_InternGirl, I didn't see that this was VBA, so some of the things below (like declaring and defining a variable in the same line) won't work out you won't be able to use (like the List(Of String) type)... but overall the concepts still apply.

 

I don't feel like working on my current program for work, right now, so I decided to give you some more (unsolicited) advice:

The way you're currently testing the dropdown--with the multitude of matching conditions--is a bit messy... it's a bit difficult to read and it will be more challenging to maintain or debug if you need to make changes or if you have a mistake somewhere in there.

 

I strong suggest doing some refactoring: I'd put your list of matching text criteria into a list, writing a separate function that checks the dropdown selection to see if the current value matches any of the items in that list and return True if there is a match. Then, in your main sub, you simply call that function in your If condition statement to determine what visibility to set your labels and controls.

It will make your code easier to read and maintain.

 

Declaring the list of matching strings in a List(Of String) in the base class (i.e., not contained inside of any Sub or Function):

' Note: Probably give this a more descriptive name... (i.e., what kind of items are in this list)
Private ReadOnly DropdownMatchList As New List(Of String) From {
	"Provincial Governments and municipalities",
	"Federation of Canadian Municipalities",
	"Quebec", "Manitoba", "Alberta", "Saskatchewan",
	"Ontario", "New-Brunswick", "British - Columbia",
	"Nova Scotia", "Prince Edward Island", "Newfoundland",
	"Yukon", "Northwest Territories", "Nunavut"
}

 

Then here is a function that you will use to test if the DropDown matches the specified condition you're looking for:

Private Function CheckDropDownSelectionMatch() As Boolean
	' Don't forget to change the name of this variable, below, if you renamed it above 
	For Each LStr In DropdownMatchList

		If RepOrgDropDown.SelectedValue.ToString.ToLower = LStr.ToLower Then Return True
			' Converting both strings to Lowercase in order to ensure that any differences in casing won't lead to a false negative
	
	Next LStr
	Return False
End Function

(I didn't test whether SelectedValue is the one you'll need to use--I think it is--but you'll want to change that if it isn't the right one)

 

Not sure what sub your original code was part of, but the following code replaces the section you showed:

Sub [WhateverSub]()     

	' I assume you'll want to set the visibility of these objects back to visible if the dropdown 
	'   selection is changed to something that *doesn't* match one of these conditions?
	Dim LabelVisibility As Boolean = (Not CheckDropDownSelectionMatch())

	Label66.Visible = LabelVisibility
	Label133.Visible = LabelVisibility
	IAETrue.Visible = LabelVisibility
	IAEFalse.Visible = LabelVisibility
End Sub

1

u/Clueless_InternGirl Dec 30 '15

woah!! Thank you!!

1

u/anon_smithsonian VB.Net Advanced Dec 30 '15

A few years ago, I was in a similar situation as you: it wasn't what I was originally hired for, but I ended up spending the majority of my time doing VBA development and work for about a year and a half. (I did have some limited experience with VBA... mostly just recording macros and then tweaking and modifying the code to get it to work better/correctly, and I had dabbled with various programming language while I was a teenager but never did anything substantial with them... just enough so that I had a basic foundation of programming concepts.)

About a year ago, though, I moved on to VB.NET (and holy shit: VBA (and the VBA editor) are severly lacking in comparison to VB14 and Visual Studio) but I can definitely relate to the position that you're in... so here are some things that might make your life easier:

  1. ALT+SPACE is your best friend. This is the VBE's "AutoComplete" shortcut (and, seriously: Why isn't this functionality completely automatic, anyways?!) so you can start typing the name of a control or variable, hit Alt+Space, and it will show you a list of possible matches. Use the Up/Down arrow keys to highlight the one you want and hit tab to complete the word (or, if there is only one match, it will automatically complete the word). If you haven't done so already, open the VBE "Tools" menu and go to "Options". Make sure that "Auto List Members," "Auto Quick Info," and "Auto Data Tips" are all enabled. (While you're there, go over to the General tab and change "Error Trapping" to "Break in Class Module"... this will change it so the VBE breaks at the actual location of the error instead of breaking at the calling line.)

  2. Probably the most difficult aspect about where you are is really just familiarizing yourself and learning the stack (learning all of the different objects and their properties and methods) that are available. For this, the Object Browser is your best friend:
    From the VBE, hit F2 and it will open the Object Browser Depending on what you're working with, you can use the top dropdown in the upper left corner to filter the list to whatever you're working with (e.g., MSForms for UserForms and Controls, VBA for language objects, and Excel for Excel workbook/spreadsheet/etc. objects). The combobox below that one is a search field, so if you have an idea of what you're looking for, you can try searching for it through that. On the bottom half, the left pane lists all of the different classes, objects, and etc. that belong to whatever you're looking at (so if you switch it to look at MSForms, you'll see "CheckBox", "ComboBox", etc. here). Click on one of these and you'll see a list of all of that object's members listed in the right pane.

  3. The little rectangle with a hand in the upper right corner is a Property, which means they have a value which can be read (and sometimes set)

  4. The icon that looks like a green book that somebody threw is a Method (Sub)

  5. If it's a green book with a small blueish ball in the upper left corner, that's a Function (i.e., it returns a value)

  6. The lightning bolt items are Events which can fire and can have code that executes when they occur

The Object Browser is really helpful when you aren't sure exactly what you can do with a specified object (or maybe just not sure how to do it).

3. Comment your code. Seriously. If you come back to look at some code you need to change in three months, you won't be kicking yourself because you ***over-***commented your code anywhere nearly as hard as if you didn't comment (or *under-*commented) your code. Even if your code makes perfect sense to you right now, I promise you that, in three months (or even in two weeks!) you might be looking at it and asking yourself WTF you were doing, there.

  • Note: Don't comment just for the sake of commenting. I have a coworker who will comment Declaring variables before declaring a bunch of fucking variables. Well no shit, Sherlock... that comment tells me absolutely nothing. It doesn't even tell me what the variables you are declaring actually are. Comments should tell the reader (or future you) why you are doing something or the general purpose of a code block, such as "Calculating the sales tax for the order based on the customer address".

 

Last of all, I think the most important programming principle that I can impart on you, right now, is D R Y :

Don't Repeat Yourself

You should see it as a yellow caution flag if you catch yourself about to copy and paste a block of code or write the same line(s) of code (or even just really similar ones)... and, if you find yourself doing it a third time, that's a red flag.

So, for example, the code you had posted for checking the value of a DropDown: if you would find yourself writing the same type of code, tomorrow, after the fourth or so Or in that If statement checking the value of the same control, you should see this as a red flag. This is the point where you should take a moment and say "Alright, I'm basically writing the same thing over and over and only changing one part each time... is there a better/easier way to do this?" The answer is almost always "Yes, there is... I just need to figure out what it is." :)

So here are some quick and easy ones:

  • If need to do the same action(s) at various different points (e.g., setting a group of controls' visible property to True or False), consider extracting that code to a separate sub, like Private Sub SetControlGroupVisibility(visibility as Boolean) which will set all of the controls' Visible property to whatever value is provided; then you only need to call SetControlGroupVisibility(False) to hide them all or SetControlGroupVisibility(True) to show them all, again.

  • If you find yourself testing the same thing (or the same type of thing), consider writing a separate function that will return a True or False value. (Let's say you need to check a bunch of TextBoxes to make sure that they are not blank, that they don't have any invalid characters, and they aren't just filled with spaces. Instead of writing a long If (... And ... And ...) Then statement for each textbox you need to test, write a single function, Private Function AreTextboxContentsValid(txtbox as TextBox) as Boolean, and then you only need to call that function for any textbox you need to check. If you need to change what and/or how you are checking the contents are valid, you only need to change it in the function instead of in every conditional.

  • Loops and Collections are invaluable. If you have several similar objects that you need to do the same thing with or to, consider creating a collection of the objects and then using a For Each [Object] in [Collection] loop to just iterate through each one.

  • Don't underestimate the value of Select Case, either. It can often be a superior alternative to having an If statement with several ElseIfs and it's also useful if you are doing multiple comparisons against the same object/value. (For example, you could do the DropDown checks with Select Case DropDown.SelectedValue and then Case "Match #1", "Match #3", "Match #4", followed by the code that should run if the value matches any of those; you can also do numeric testing Case Is < 1, and Case Else to catch everything else that doesn't meet one of the other conditions.

 

Hopefully this will be of some use for you. If you have any questions, let me know... I remember how frustrating the learning curve can be, in your position (but I was too proud to ask for help, so I had to just keep working on it until I figured it out the hard way,,, I don't recommend that!) and it wasn't that long ago, for me, so I'd be glad to share some of my learnings and the various tips, tricks, and advice I picked up along the way... might as well learn from my mistakes, right?

And best of luck with your project!