Vba excel properties list

Is there a way to get a list of all valid properties for a given object?

If I wanted to start at cell a1, and go down and assign a1, a2, a3, all of the valid properties for let’s say a worksheet object for example, is that something that can be done? I can’t find any:

list = object.enumproperties

Any ideas?

Teamothy's user avatar

Teamothy

1,9903 gold badges15 silver badges24 bronze badges

asked Nov 5, 2013 at 6:36

user2021539's user avatar

2

Tools — References — TypeLib Information.

Then:

Sub DumpProperties(ByVal o As Object)

  Dim t As TLI.TLIApplication
  Set t = New TLI.TLIApplication

  Dim ti As TLI.TypeInfo
  Set ti = t.InterfaceInfoFromObject(o)

  Dim mi As TLI.MemberInfo, i As Long
  For Each mi In ti.Members
    i = i + 1
    ActiveSheet.Cells(i, 1).Value = mi.Name
  Next

End Sub

answered Nov 5, 2013 at 6:47

GSerg's user avatar

GSergGSerg

75.3k17 gold badges160 silver badges340 bronze badges

16

Option Explicit

Private Type GUID
    Data1 As Long
    Data2 As Integer
    Data3 As Integer
    Data4(0 To 7) As Byte
End Type

Private Type TTYPEDESC
    #If Win64 Then
        pTypeDesc As LongLong
    #Else
        pTypeDesc As Long
    #End If
    vt            As Integer
End Type

Private Type TPARAMDESC
    #If Win64 Then
        pPARAMDESCEX  As LongLong
    #Else
        pPARAMDESCEX  As Long
    #End If
    wParamFlags       As Integer
End Type

Private Type TELEMDESC
    tdesc  As TTYPEDESC
    pdesc  As TPARAMDESC
End Type

Type TYPEATTR
        aGUID As GUID
        LCID As Long
        dwReserved As Long
        memidConstructor As Long
        memidDestructor As Long
        #If Win64 Then
            lpstrSchema As LongLong
        #Else
            lpstrSchema As Long
        #End If
        cbSizeInstance As Integer
        typekind As Long
        cFuncs As Integer
        cVars As Integer
        cImplTypes As Integer
        cbSizeVft As Integer
        cbAlignment As Integer
        wTypeFlags As Integer
        wMajorVerNum As Integer
        wMinorVerNum As Integer
        tdescAlias As Long
        idldescType As Long
End Type


Type FUNCDESC
    memid As Long
    #If Win64 Then
        lReserved1 As LongLong
        lprgelemdescParam As LongLong
    #Else
        lReserved1 As Long
        lprgelemdescParam As Long
    #End If
    funckind As Long
    INVOKEKIND As Long
    CallConv As Long
    cParams As Integer
    cParamsOpt As Integer
    oVft As Integer
    cReserved2 As Integer
    elemdescFunc As TELEMDESC
    wFuncFlags As Integer
End Type

#If VBA7 Then
    Private Declare PtrSafe Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As LongPtr)
    Private Declare PtrSafe Function DispCallFunc Lib "oleAut32.dll" (ByVal pvInstance As LongPtr, ByVal offsetinVft As LongPtr, ByVal CallConv As Long, ByVal retTYP As Integer, ByVal paCNT As Long, ByRef paTypes As Integer, ByRef paValues As LongPtr, ByRef retVAR As Variant) As Long
    Private Declare PtrSafe Sub SetLastError Lib "kernel32.dll" (ByVal dwErrCode As Long)
#Else
    Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (Destination As Any, Source As Any, ByVal Length As Long)
    Private Declare Function DispCallFunc Lib "oleAut32.dll" (ByVal pvInstance As Long, ByVal offsetinVft As Long, ByVal CallConv As Long, ByVal retTYP As Integer, ByVal paCNT As Long, ByRef paTypes As Integer, ByRef paValues As Long, ByRef retVAR As Variant) As Long
    Private Declare Sub SetLastError Lib "kernel32.dll" (ByVal dwErrCode As Long)
#End If




Function GetObjectFunctions(ByVal TheObject As Object, Optional ByVal FuncType As VbCallType) As Collection


    Dim tTYPEATTR As TYPEATTR
    Dim tFUNCDESC As FUNCDESC

    Dim aGUID(0 To 11) As Long, lFuncsCount As Long
    
    #If Win64 Then
        Const vTblOffsetFac_32_64 = 2
        Dim aTYPEATTR() As LongLong, aFUNCDESC() As LongLong, farPtr As LongLong
    #Else
        Const vTblOffsetFac_32_64 = 1
        Dim aTYPEATTR() As Long, aFUNCDESC() As Long, farPtr As Long
    #End If
    
    Dim ITypeInfo As IUnknown
    Dim IDispatch As IUnknown
    Dim sName As String, oCol As New Collection
    
    Const CC_STDCALL As Long = 4
    Const IUNK_QueryInterface As Long = 0
    Const IDSP_GetTypeInfo As Long = 16 * vTblOffsetFac_32_64
    Const ITYP_GetTypeAttr As Long = 12 * vTblOffsetFac_32_64
    Const ITYP_GetFuncDesc As Long = 20 * vTblOffsetFac_32_64
    Const ITYP_GetDocument As Long = 48 * vTblOffsetFac_32_64

    Const ITYP_ReleaseTypeAttr As Long = 76 * vTblOffsetFac_32_64
    Const ITYP_ReleaseFuncDesc As Long = 80 * vTblOffsetFac_32_64


    aGUID(0) = &H20400: aGUID(2) = &HC0&: aGUID(3) = &H46000000
    CallFunction_COM ObjPtr(TheObject), IUNK_QueryInterface, vbLong, CC_STDCALL, VarPtr(aGUID(0)), VarPtr(IDispatch)
    If IDispatch Is Nothing Then MsgBox "error":   Exit Function

    CallFunction_COM ObjPtr(IDispatch), IDSP_GetTypeInfo, vbLong, CC_STDCALL, 0&, 0&, VarPtr(ITypeInfo)
    If ITypeInfo Is Nothing Then MsgBox "error": Exit Function
    
    CallFunction_COM ObjPtr(ITypeInfo), ITYP_GetTypeAttr, vbLong, CC_STDCALL, VarPtr(farPtr)
    If farPtr = 0& Then MsgBox "error": Exit Function

    CopyMemory ByVal VarPtr(tTYPEATTR), ByVal farPtr, LenB(tTYPEATTR)
    ReDim aTYPEATTR(LenB(tTYPEATTR))
    CopyMemory ByVal VarPtr(aTYPEATTR(0)), tTYPEATTR, UBound(aTYPEATTR)
    CallFunction_COM ObjPtr(ITypeInfo), ITYP_ReleaseTypeAttr, vbEmpty, CC_STDCALL, farPtr
    
    For lFuncsCount = 0 To tTYPEATTR.cFuncs - 1
        Call CallFunction_COM(ObjPtr(ITypeInfo), ITYP_GetFuncDesc, vbLong, CC_STDCALL, lFuncsCount, VarPtr(farPtr))
        If farPtr = 0 Then MsgBox "error": Exit For
        CopyMemory ByVal VarPtr(tFUNCDESC), ByVal farPtr, LenB(tFUNCDESC)
        ReDim aFUNCDESC(LenB(tFUNCDESC))
        CopyMemory ByVal VarPtr(aFUNCDESC(0)), tFUNCDESC, UBound(aFUNCDESC)
        Call CallFunction_COM(ObjPtr(ITypeInfo), ITYP_ReleaseFuncDesc, vbEmpty, CC_STDCALL, farPtr)
         Call CallFunction_COM(ObjPtr(ITypeInfo), ITYP_GetDocument, vbLong, CC_STDCALL, aFUNCDESC(0), VarPtr(sName), 0, 0, 0)
        Call CallFunction_COM(ObjPtr(ITypeInfo), ITYP_GetDocument, vbLong, CC_STDCALL, aFUNCDESC(0), VarPtr(sName), 0, 0, 0)

        With tFUNCDESC
            If FuncType Then
                If .INVOKEKIND = FuncType Then
                    'Debug.Print sName & vbTab & Switch(.INVOKEKIND = 1, "VbMethod", .INVOKEKIND = 2, "VbGet", .INVOKEKIND = 4, "VbLet", .INVOKEKIND = 8, "VbSet")
                    oCol.Add sName & vbTab & Switch(.INVOKEKIND = 1, "VbMethod", .INVOKEKIND = 2, "VbGet", .INVOKEKIND = 4, "VbLet", .INVOKEKIND = 8, "VbSet")
                End If
            Else
                'Debug.Print sName & vbTab & Switch(.INVOKEKIND = 1, "VbMethod", .INVOKEKIND = 2, "VbGet", .INVOKEKIND = 4, "VbLet", .INVOKEKIND = 8, "VbSet")
                oCol.Add sName & vbTab & Switch(.INVOKEKIND = 1, "VbMethod", .INVOKEKIND = 2, "VbGet", .INVOKEKIND = 4, "VbLet", .INVOKEKIND = 8, "VbSet")
            End If
        End With
        sName = vbNullString
    Next
    
    Set GetObjectFunctions = oCol

End Function



#If Win64 Then
    Private Function CallFunction_COM(ByVal InterfacePointer As LongLong, ByVal VTableOffset As Long, ByVal FunctionReturnType As Long, ByVal CallConvention As Long, ParamArray FunctionParameters() As Variant) As Variant

    Dim vParamPtr() As LongLong
#Else
    Private Function CallFunction_COM(ByVal InterfacePointer As Long, ByVal VTableOffset As Long, ByVal FunctionReturnType As Long, ByVal CallConvention As Long, ParamArray FunctionParameters() As Variant) As Variant

    Dim vParamPtr() As Long
#End If

    If InterfacePointer = 0& Or VTableOffset < 0& Then Exit Function
    If Not (FunctionReturnType And &HFFFF0000) = 0& Then Exit Function

    Dim pIndex As Long, pCount As Long
    Dim vParamType() As Integer
    Dim vRtn As Variant, vParams() As Variant

    vParams() = FunctionParameters()
    pCount = Abs(UBound(vParams) - LBound(vParams) + 1&)
    If pCount = 0& Then
        ReDim vParamPtr(0 To 0)
        ReDim vParamType(0 To 0)
    Else
        ReDim vParamPtr(0 To pCount - 1&)
        ReDim vParamType(0 To pCount - 1&)
        For pIndex = 0& To pCount - 1&
            vParamPtr(pIndex) = VarPtr(vParams(pIndex))
            vParamType(pIndex) = VarType(vParams(pIndex))
        Next
    End If

    pIndex = DispCallFunc(InterfacePointer, VTableOffset, CallConvention, FunctionReturnType, pCount, _
    vParamType(0), vParamPtr(0), vRtn)
    If pIndex = 0& Then
        CallFunction_COM = vRtn
    Else
        SetLastError pIndex
    End If

End Function

Excel VBA Tutorial about Object PropertiesI’ve got to confess something to you:

I cover the topic of VBA objects extensively in Power Spreadsheets, including here and here. However, when working in Visual Basic for Applications, you can’t really do anything meaningful by knowing only what I explain in those Excel tutorials.

Let me explain what I mean:

There is no doubt that the concept of objects is central to VBA. After all, VBA is loosely based on the concept of object-oriented programming.

However, as explained by John Walkenbach in Excel VBA Programming for Dummies:

(…) you can’t do anything useful by simply referring to an object (…).

In order to actually start “doing something” with an object, you need to understand at least 1 of the following topics:

  • Object properties.
  • Object methods.

To be more precise:

In order to become great in VBA, you actually need to understand and master both properties and methods. This Excel tutorial covers 1 of these topics:

Object properties.

More particularly, in this blog post you’ll read about the following topics:

If you’re interested in reading about object methods, please click here.

Let’s start learning about the topic of VBA object properties by remembering what they actually are:

What Are VBA Object Properties

As I explain in this Excel VBA tutorial, properties are the named attributes of an object or, in other words, what you can use to describe an object, such as its:

  • Attributes.
  • Characteristics.
  • Qualities.

In Excel 2013 VBA and Macros, Excel authorities Bill Jelen and Tracy Syrstad liken properties to adjectives. In the regular English language, adjectives describe or clarify a noun.

In the context of Visual Basic for Applications, objects are the equivalent of nouns. Therefore, within VBA, properties (adjectives) describe objects (nouns).

The above comments apply to object collections (which are objects themselves) as well. In other words, collections also have properties that describe them.

As mentioned in Mastering VBA for Microsoft Office 2013, every object within Visual Basic for Applications has properties. This makes sense, after all, properties determine things such as:

  • How the object looks like.
  • How the object behaves like.
  • Whether you can or can’t see the object.

In fact, most objects have several properties, with each property determining a different characteristic of the object.

Richard Mansfield explains, in Mastering VBA for Microsoft Office 2013, how objects of the same type have the same set of properties. However, each of the individual objects stores their own individual values for each of those properties. In other words:

(…) each object is independent of the other objects.

As explained in Excel VBA Programming for Dummies, Excel 2013 Power Programming with VBA and Excel 2013 VBA and Macros, VBA allows you to do the following 2 things with the properties of an object:

Object Property Use #1: Read Them

This means, in other words, fetch or return the current settings of an object property.

As explained in the Excel 2013 Bible, you’d generally examine the current property of an object for purposes of taking a particular course of action depending on the value of that property.

However, properties can also be used to return objects. In fact, most VBA objects are actually accessed through the use of properties. For example, the macro samples that are used below in this Excel VBA tutorial use the Range.Interior property for these purposes.

Object Property Use #2: Modify Them

This means, more precisely, change the current setting of that property and set it to a certain value.

Based on the 2 uses above, you can classify VBA object properties in read/write, read-only or write-only properties. Let’s see what each of these means:

Read And Write VBA Object Properties

As mentioned by Richard Mansfield in Mastering VBA for Microsoft Office 2013, “many properties are read/write“. This means that you can carry out both of these actions (read or modify) in connection with such properties.

However, as you’ll see below, not all properties are like this. There are both read-only and write-only properties. As implied by the description, you can only:

  • Read (but not set) read-only properties.
  • Set (but not read) write-only properties.

I show you step-by-step examples of how to do both of this below.

How Do You Work With A VBA Object Property

In order to understand the syntax you should use in order to work with a VBA object property, let’s use 2 practical examples:

  • Example #1: We take a look at an example where the VBA code changes the current setting of a property.
  • Example #2: We see an example of a macro that reads and displays the current settings of that same property.

In both cases, I’ll provide additional information about the particular case. However, the general rule for referring to a VBA object property is clearly explained by John Walkenbach in the Excel 2013 Bible:

You refer to a property in your VBA code by placing a period (a dot) and the property name after the object’s name.

In other words, you generally:

  • Refer to the object and then to the property, as mentioned in Excel Macros for Dummies.
  • Separate the object from the property with a period (.).

As explained below, whenever you’re setting the value of a particular object property, you generally include an additional element: the property value you’re setting. However, even in such cases, you continue to use the basic syntax described above.

Let’s go to the examples and see how this syntax looks in practice:

VBA Object Property Syntax Case #1: Setting A Property Value

The following macro (called Find_Format_Formulas) finds, selects and formats all formulas in the active Excel worksheet. More precisely, this macro highlights in light yellow any cell that contains a formula.

VBA Sub procedure to find and format formulas

This Excel VBA Properties Tutorial is accompanied by an Excel workbook containing the data and macros I use (including the Find_Format_Formulas macro). You can get immediate free access to this example workbook by subscribing to the Power Spreadsheets Newsletter.

Let’s take a look at the practical results of executing the Find_Format_Formulas macro:

I’ve typed the following (random) formula using the SUM function. Notice how none of the cells that appear in the screenshot is highlighted.

Excel with sample SUM formula

The following screenshot shows the same cells after the Find_Format_Formulas macro is executed. Notice how, now, the cell with the formula is highlighted in light yellow.

Macro highlighting Excel formula

Described in plain English, the macro has changed the fill color of the cell.

Let’s describe what is happening in a slightly more structured manner to see what Visual Basic for Applications has done:

  • The cell itself is an object.
  • The fill color is an attribute that you can use to describe the cell. In other words, the fill color is a VBA object property.
  • The Find_Format_Formulas macro has modified the value of the fill color property.

Let’s go back to the VBA code of the Find_Format_Formulas and focus on the statement that determines the new value of the fill color VBA property. This statement is:

my_Range.Interior.ColorIndex = 36

The following screenshot shows the location of this statement within the Find_Format_Formulas Sub procedure:

VBA code with example of VBA object property

Let’s take a close look at each of the elements in this statement to understand its structure:

Element #1: Object (my_Range.Interior)

my_Range is an object variable. Object variables serve as a substitute for actual objects.

In this example, my_Range is a Range object.

The Range.Interior property is used for purposes of returning the interior of the relevant range. In the case of this example, this is the interior of the cells that contain formulas. This, in turn, is an Interior object.

In other words, this first element represents the interior of the cells that contain formulas. This the object whose attribute (color, in the example above) changes. This sentence can be reworded in VBA terms as follows:

my_Range.Interior represents the object whose property (fill color) is modified.

Element #2: Dot (.) Operator

As a general rule, Visual Basic for Applications uses the dot (.) operator to connect and separate the various items you can work with.

You can think of the dot (.) operator as the rough equivalent to the word “of” in plain English. The following are the basics of the dot (.) notation:

  • It’s hierarchical and usually begins with an object.

    As a consequence of the above, the hierarchy of VBA objects in Excel is of particular importance.

  • Once you’ve identified the object, you include a dot (.) to separate the object from the relevant property or method.

    Notice how, in the example above, we’ve used additional dots when identifying the object (my_Range.Interior). This happens because, depending on matters such as how you craft your object references and which particular object you’re working with, you may have to use additional dots when identifying the object.

  • After the dot, you type the relevant property or method.

In the case of this Excel tutorial, you already know that we’re working with properties (not methods). Therefore, what the next element in the statement is shouldn’t be a surprise to you:

Element #3: Property (ColorIndex)

You can use the ColorIndex property to either return or set the color of the relevant object (usually a border, font or interior).

In the example above, we’re modifying the actual property (not reading it). Therefore, let’s take a look at the last element of the statement to see how the property value is set…

Element #4: Property Value (= 36)

In order to be able to modify the value of a property, you must work with arguments. In Excel 2013 Power Programming with VBA, John Walkenbach explains that not all properties use arguments. However, some (such as ColorIndex) do.

In the cases where a property uses arguments, the main purpose of such argument is to specify the value of the property. According to Walkenbach, property arguments is an issue that often “leads to confusion among new VBA programmers”.

However, the basic syntax for specifying arguments for VBA object properties isn’t particularly complicated. In fact, the general rule is as simple as shown above:

You use an equal sign (=) to separate the property name from the property value.

As mentioned in Excel 2013 VBA and Macros and Microsoft Excel 2013 In Depth, the equal sign (=) is a good indication that you’re looking at a property value. If you see a colon (:) before the equal sign (:=), you’re likely looking at a method.

In other words, to set the value of a property, you:

  • Refer to the property.
  • Place an equal sign (=) after the VBA object property name.
  • Set the value of the object property.

Therefore, in the statement above, the ColorIndex property is used to set the color of the Interior object identified in the first part of the statement (the interior of the cells that contain formulas) to color 36 of the color palette. Color 36 is the light yellow that appears in the screenshot above.

In other words, the basic syntax you must follow in order to be able to set the value of a VBA property (as partially explained above) is:

Object.Property = Property_Value

The first part (Object.Property) is the general syntax that I describe above and that you use when reading a property value. In other words, this is the basic structure you need to know.

When setting the value of an object property, you only need to add the last elements (= Property_Value): an equal sign and the property value.

You won’t be able to modify absolutely all object properties using Visual Basic for Applications by using the syntax described above. There are some object properties that are read-only. For example:

  • In the Excel 2013 Bible, John Walkenbach lists the Row and Column properties of a single-cell Range object.
  • In Excel Macros for Dummies, Michael Alexander mentions the “Text property of cell”.

The consequence of a property being read-only, as you can probably imagine, is that:

  • You can read the object property…
  • But you can’t modify it.

Let’s turn, then, to the second case of property use:

VBA Object Property Syntax Case #2: Reading A Property Value

Let’s go back to the Excel workbook in which the sample Find_Format_Formulas macro was run:

The following screenshot shows the only worksheet of that workbook. Notice how there’s only 1 cell (B5) whose fill has been set to light yellow by the Find_Format_Formulas macro:

Example of modified object property in Excel

The following Sub procedure (named Display_ColorIndex) shows a message box displaying the value of the ColorIndex property for cell B5 of the worksheet named VBA Object Properties. The basic structure of this piece of VBA code is suggested by John Walkenbach in both Excel VBA Programming for Dummies and Excel 2013 Power Programming with VBA.

Example macro that reads object property setting

The following is the message box that Excel displays when the Display_ColorIndex macro is executed:

Message box with ColorIndex property

The value displayed (36) makes sense. Cell B5 of the worksheet named VBA Object Properties is the only cell with a light yellow fill. We already know from the previous macro Find_Format_Formulas, that this light yellow is color 36 in the color palette for the ColorIndex property.

Let’s focus, once again, on the most relevant section of the macro. The following image shows the part of the statement that is responsible for reading the value of the ColorIndex property of cell B5’s interior:

Syntax for VBA object property

This probably looks familiar.

You’ll notice that this is materially the same structure that we saw before when looking at how to modify the settings of an object property. Let’s take a look at the 3 elements of this statement to make it even clearer:

Element #1: Object (Worksheets(“VBA Object Properties”).Range(“B5”).Interior)

This structure is substantially similar to that I describe above. In other words:

  • The first part (Worksheets(“VBA Object Properties”).Range(“B5”)) of this section follows the general way of crafting references to Excel’s Range object.
  • The Range.Interior property is used for purposes of returning an Interior object. In this case, this object is the interior of cell B5 in the worksheet called VBA Object Properties.

    There is, however, a substantial difference: the Display_ColorIndex macro has no object variables whereas the Find_Format_Formulas macro in the previous section does.

Element #2: Dot (.) Operator

The dot (.) operator serves exactly the same purpose as in the Find_Format_Formulas macro above. In other words, it’s used to connect and separate element #1 above (the object) with element #3 below (the property).

Element #3: Property (ColorIndex)

The ColorIndex property can be used to set the color of an object (such as the interior of a cell). This is what the property does in the Find_Format_Formulas above.

However, ColorIndex can also be used to return the color of an object. This is the way in which the property is used in the Display_ColorIndex macro under analysis.

This analysis confirms what we’d seen above. More precisely, it confirms that the basic syntax that you can use to refer to Excel VBA properties is the same regardless of whether you are changing or examining the setting of that particular property. Just as a reminder, this basic syntax is:

Object.Property

I suggest you exercise care when creating references to objects and properties. Even though the basic syntax isn’t complicated, is important to make sure that you’re correctly identifying the relevant collections and the appropriate object from within the collection, as well as correctly using properties to refer to an object. If you fail to do this properly, you’ll usually receive an error message when trying to execute the macro.

For example, let’s assume that, instead of typing “VBA Object Properties” to identify the object from within the Worksheets collection I want to work with, I type the default “Sheet1”. In other words, the VBA code of the Display_ColorIndex macro looks as follows:

VBA code with wrong object reference

Sheet1 doesn’t exist within the example workbook that accompanies this Excel VBA Properties tutorial. You can get immediate free access to this example workbook by subscribing to the Power Spreadsheets Newsletter.

Therefore, when I try to execute the Display_ColorIndex macro, Visual Basic for Applications returns the following error:

VBA error caused by wrong object reference

Obtaining an error in such a case makes sense. After all, as John Walkenbach explains in Excel VBA Programming for Dummies:

VBA just follows instructions, and it can’t work with a sheet that doesn’t exist.

Finally, remember that there are some instances in which you’ll not be able to read an object’s properties. In those cases, the property is deemed to be write-only.

In Excel 2013 Power Programming with VBA, John Walkenbach explains how this is the case, for example, in connection with the Value and Formula properties of certain cell Range objects. More precisely, you can only read the Value and Formula properties for a single-cell objects. This limitation (however) only applies to reading the property. You can actually modify the Value and Formula properties for multi-cell Range objects.

The consequences of a property being write-only are the following:

  • You can’t read the object property…
  • But you can modify it.

This is exactly the opposite of what happens in the case of read-only properties, which are described above.

Before we move on to the next topic, let’s take a quick look at 2 final clarifications regarding the syntax you should use when working with VBA object properties:

Default Object Properties And Properties That Return Values

Most VBA objects have a particular property that is their default. Therefore, theoretically, you can omit certain parts of the code. In other words, you can simply make reference to the VBA object, without including the property after it.

However, as mentioned in Excel 2013 Power Programming with VBA, including the VBA property explicitly in your code is a good programming practice. This is the case even if the property you’re making reference to is the default property.

Finally, note that Excel 2013 Power Programming also explains that in the case of properties that return a value, you must place parentheses around the arguments. This is an exception to the rules that I explain in the sections above.

Now that you know how to refer to and work with Excel VBA object properties, you may wonder…

How Do You Know Which Properties Are Available For A Particular VBA Object

According to John Walkenbach, there are:

(…) literally thousands of properties and methods available.

Fortunately, you won’t need to work with most of them. Most likely, you’ll end up working with a relatively small portion of the available VBA object properties again and again.

Additionally, even though each VBA object has its own properties, some properties are common to several objects. The following are some of the examples of common VBA properties. These examples are further explained in Excel VBA Programming for Dummies and Mastering VBA for Microsoft Office 2013:

  • The Visible property.
  • The Name property.
  • The Saved property.

However, since you’re likely to (from time to time) need some help to find out the properties that are available for a particular VBA object, let’s take a look at 3 ways in which you can get this information.

And in any case, remember that the macro recorder can help you identify/see what you need“.

Method #1: Use The Object Browser

As implied by its name, the Object Browser within the Visual Basic Editor allows you to browse through VBA objects. Perhaps more importantly, it shows you the properties, methods and events of each of those objects.

You can access the Object Browser in any of the following ways:

  • Click on the Object Browser button in the Standard toolbar.

    Access Object Browser in Visual Basic Editor

  • Go to the View menu and select “Object Browser”.

    Object Browser in Visual Basic Editor

  • Use the keyboard shortcut “F2”.

Once the Visual Basic Editor is displaying the Object Browser, you can have the VBE display all the relevant information about a particular object by following these 2 easy steps:

Step #1: Select The Excel Library

On the top left-hand corner of the Object Browser, you’ll notice a drop-down list that says “<All Libraries>”.

Object Browser to see properties

Click on this drop-down list and select “Excel”.

Select Excel library in VBE

Step #2: Select The Appropriate Object Class

Once you’ve selected the Excel library, the Object Browser displays all the Excel objects in the left side of the screen. Simply search for the one you want and click on it.

Once you’ve clicked on a particular object, the Object Browser lists all the properties and methods available for that object on the right side of the screen.

For example, the following image shows how the Object Browser looks like when I click on “Interior”. Notice how the ColorIndex property (which is used in both sample macros within this Excel tutorial) appears on the right side.

ColorIndex property for Interior object

Method #2: Use The Microsoft Developer Network

The Microsoft Dev Center contains an extensive amount of information about VBA objects and properties. The easiest way to find information about a particular object using this tool is by following these 3 simple steps:

Step #1: Enter An Object In The Visual Basic Editor

This step is self-explanatory. Simply type the name of the object you wish to find more information about.

Let’s assume that we want to find more information about the Range object while working in the sample Display_ColorIndex macro. Therefore, the VBA code looks as follows:

Object in VBA code

Step #2: Place The Cursor Within The Object Name

This step doesn’t require much further explanation.

The following screenshot shows how this looks like when the relevant object is Range and we’re working with the Display_ColorIndex macro:

Range object within VBA code

Step #3: Press The F1 Key

The F1 key is the keyboard shortcut to open the help system. You can find a comprehensive list of keyboard shortcuts in this blog post.

If the Visual Basic Editor finds that there are several possible matches for the keyword you’ve selected, it asks you to select a topic. This is what happens in the case of Range.

Context Help to find information about VBA object

If there’s no ambiguity (it’s clear which word you want to get information about), or once you’ve selected a topic in the Context Help dialog (as in the case above), you’re led to the relevant page within the Microsoft Developer Network.

For example, in the case above, once I choose the first option (“Range(object)”) and press the Help button on the upper right corner of the Context Help dialog, the Microsoft Developer Network displays the page that corresponds to this object. You can have the Microsoft Developer Network display all the properties that correspond to the Range object by clicking on, or expanding the menu, “Properties” on the left sidebar.

Range Object in Microsoft Developer Network

Method #3: Make The Visual Basic Editor Display A List Of Properties

Probably the easiest way of getting an idea of the properties of a particular object is by getting help from the Visual Basic Editor.

The VBE displays a list with all the items (such as properties and methods) that can be associated with a particular object once you’ve typed the dot (.) that follows that VBA object.

Let’s take a look at an example by going back to the VBA code of the Find_Format_Formulas macro. The following screenshot shows how the Visual Basic Editor displays a list of properties and methods immediately after I type the dot (.) that follows “my_Range.Interior”.

List of object properties in VBE

In order to be able to take advantage of this setting, your Visual Basic Editor must have the Auto List Members setting option enabled. I explain how to do this here.

This helps you get an idea of what are the properties and methods (in the example above, the VBE shows only properties) that you have available in a particular situation.

Conclusion

The concept of object properties is central to Visual Basic for Applications. Therefore, if you plan on working with VBA, you’ll spend a great deal of time dealing with object properties.

Despite being a relatively basic concept, the topic of properties can be quite overwhelming. As mentioned above, there are thousands of object properties available throughout Visual Basic for Applications.

The good news is that you don’t have to know absolutely all VBA object properties by heart in order to be able to do great work with Visual Basic for Applications. As long as you have a good understanding of the following 2 basic topics, you have a good base to start moving forward:

  • How to refer to and work with object properties.
  • How to search for and find the object properties you need.

Both of these matters were covered in this Excel tutorial.

Books Referenced In This Excel Tutorial

  • Alexander, Michael (2015). Excel Macros for Dummies. Hoboken, NJ: John Wiley & Sons Inc.
  • Jelen, Bill (2013). Excel 2013 In Depth. United States of America: Que Publishing.
  • Jelen, Bill and Syrstad, Tracy (2013). Excel 2013 VBA and Macros. United States of America: Pearson Education, Inc.
  • Mansfield, Richard (2013). Mastering VBA for Microsoft Office 2013. Indianapolis, IN: John Wiley & Sons Inc.
  • Walkenbach, John (2013). Excel 2013 Bible. Indianapolis, IN: John Wiley & Sons Inc.
  • Walkenbach, John (2013). Excel VBA Programming for Dummies. Hoboken, NJ: John Wiley & Sons Inc.
  • Walkenbach, John (2013). Excel 2013 Power Programming with VBA. Hoboken, NJ: John Wiley & Sons Inc.

Элемент управления пользовательской формы ListBox для выбора и ввода информации в VBA Excel. Свойства списка, его заполнение, извлечение данных, примеры кода.

Элемент управления ListBox на пользовательской форме

UserForm.ListBox – это элемент управления пользовательской формы, предназначенный для передачи в код VBA информации, выбранной пользователем из одностолбцового или многостолбцового списка.

Список используется в тех случаях, когда необходимо добавить в форму информацию, которая заранее известна, а ее отдельные позиции можно сгруппировать в список. Элемент управления ListBox оправдывает себя при небольших списках, так как большой список будет занимать много места на форме.

Использование полос прокрутки уменьшает преимущество ListBox перед элементом управления ComboBox, которое заключается в том, что при открытии формы все позиции для выбора на виду без дополнительных действий со стороны пользователя. При выборе информации из большого списка удобнее использовать ComboBox.

Элемент управления ListBox позволяет выбрать несколько позиций из списка, но эта возможность не имеет практического смысла. Ввести информацию в ListBox с помощью клавиатуры или вставить из буфера обмена невозможно.

Свойства списка

Свойство Описание
ColumnCount Указывает количество столбцов в списке. Значение по умолчанию = 1.
ColumnHeads Добавляет строку заголовков в ListBox. True – заголовки столбцов включены, False – заголовки столбцов выключены. Значение по умолчанию = False.
ColumnWidths Ширина столбцов. Значения для нескольких столбцов указываются в одну строку через точку с запятой (;).
ControlSource Ссылка на ячейку для ее привязки к элементу управления ListBox.
ControlTipText Текст всплывающей подсказки при наведении курсора на ListBox.
Enabled Возможность выбора элементов списка. True – выбор включен, False – выключен*. Значение по умолчанию = True.
Font Шрифт, начертание и размер текста в списке.
Height Высота элемента управления ListBox.
Left Расстояние от левого края внутренней границы пользовательской формы до левого края элемента управления ListBox.
List Позволяет заполнить список данными из одномерного или двухмерного массива, а также обращаться к отдельным элементам списка по индексам для записи и чтения.
ListIndex Номер выбранной пользователем строки. Нумерация начинается с нуля. Если ничего не выбрано, ListIndex = -1.
Locked Запрет возможности выбора элементов списка. True – выбор запрещен**, False – выбор разрешен. Значение по умолчанию = False.
MultiSelect*** Определяет возможность однострочного или многострочного выбора. 0 (fmMultiSelectSingle) – однострочный выбор, 1 (fmMultiSelectMulti) и 2 (fmMultiSelectExtended) – многострочный выбор.
RowSource Источник строк для элемента управления ListBox (адрес диапазона на рабочем листе Excel).
TabIndex Целое число, определяющее позицию элемента управления в очереди на получение фокуса при табуляции. Отсчет начинается с 0.
Text Текстовое содержимое выбранной строки списка (из первого столбца при ColumnCount > 1). Тип данных String, значение по умолчанию = пустая строка.
TextAlign Выравнивание текста: 1 (fmTextAlignLeft) – по левому краю, 2 (fmTextAlignCenter) – по центру, 3 (fmTextAlignRight) – по правому краю.
Top Расстояние от верхнего края внутренней границы пользовательской формы до верхнего края элемента управления ListBox.
Value Значение выбранной строки списка (из первого столбца при ColumnCount > 1). Value – свойство списка по умолчанию. Тип данных Variant, значение по умолчанию = Null.
Visible Видимость списка. True – ListBox отображается на пользовательской форме, False – ListBox скрыт.
Width Ширина элемента управления.

* При Enabled в значении False возможен только вывод информации в список для просмотра.
** Для элемента управления ListBox действие свойства Locked в значении True аналогично действию свойства Enabled в значении False.
*** Если включен многострочный выбор, свойства Text и Value всегда возвращают значения по умолчанию (пустая строка и Null).

В таблице перечислены только основные, часто используемые свойства списка. Еще больше доступных свойств отображено в окне Properties элемента управления ListBox, а все методы, события и свойства – в окне Object Browser.

Вызывается Object Browser нажатием клавиши «F2». Слева выберите объект ListBox, а справа смотрите его методы, события и свойства.

Свойства BackColor, BorderColor, BorderStyle отвечают за внешнее оформление списка и его границ. Попробуйте выбирать доступные значения этих свойств в окне Properties, наблюдая за изменениями внешнего вида элемента управления ListBox на проекте пользовательской формы.

Способы заполнения ListBox

Используйте метод AddItem для загрузки элементов в список по одному:

With UserForm1.ListBox1

  .AddItem «Значение 1»

  .AddItem «Значение 2»

  .AddItem «Значение 3»

End With

Используйте свойство List, чтобы скопировать одномерный массив значений в элемент управления ListBox.

UserForm1.ListBox1.List = Array(«Текст 1», _

«Текст 2», «Текст 3», «Текст 4», «Текст 5»)

Вместо функции Array можно использовать переменные одномерных и двухмерных массивов. При загрузке значений из двухмерного массива, требуется предварительно указать количество столбцов в списке.

Используйте свойство RowSource, чтобы загрузить в список значения из диапазона ячеек рабочего листа:

UserForm1.ListBox1.RowSource = «Лист1!A1:A6»

При загрузке данных из диапазона, содержащего более одного столбца, требуется предварительно указать количество столбцов в списке:

With UserForm1.ListBox1

  ‘Указываем количество столбцов

  .ColumnCount = 5

  .RowSource = «‘Лист со списком’!A1:E10»

End With

В качестве имени листа используется имя ярлыка. Если имя листа содержит пробелы, оно заключается в одинарные кавычки.

Подробнее о заполнении элемента управления ListBox вы можете ознакомиться в отдельной статье с наглядными примерами.

Привязка списка к ячейке

Для привязки списка к ячейке на рабочем листе используется свойство ControlSource. Суть привязки заключается в том, что при выборе строки в элементе управления, значение свойства Value копируется в привязанную ячейку.

Если привязанная к списку ячейка содержит значение одной из строк элемента управления ListBox, то при запуске пользовательской формы список откроется с выделенной строкой, содержащей это значение. Если привязанная ячейка при загрузке формы пустая, то список откроется без выделения какой-либо строки.

В случае, когда при открытии формы в привязанной к списку ячейке содержится значение, которого нет ни в одной из строк элемента управления ListBox, будет сгенерирована ошибка.

Привязать ячейку к списку можно, указав адрес ячейки в поле свойства ControlSource в окне Properties элемента управления ListBox. Или присвоить адрес ячейки свойству ControlSource в коде VBA Excel:

UserForm1.ListBox1.ControlSource = «Лист1!A2»

Теперь значение выбранной строки в списке автоматически копируется в ячейку «A2» на листе «Лист1»:

Элемент управления ListBox с привязанной ячейкой

В окне Properties адрес указывается без двойных кавычек. Если имя листа содержит пробелы, оно заключается в одинарные кавычки.

Извлечение информации из списка

Первоначально элемент управления ListBox открывается со строками, ни одна из которых не выбрана. При выборе (выделении) строки, ее значение записывается в свойства Value и Text.

Из этих свойств мы с помощью кода VBA Excel извлекаем информацию, выбранную в списке пользователем:

Dim myVar as Variant, myTxt As String

myVar = UserForm1.ListBox1.Value

‘или

myTxt = UserForm1.ListBox1.Text

Вторую строку кода можно записать myVar = UserForm1.ListBox1, так как Value является свойством списка по умолчанию.

Если ни одна позиция в списке не выбрана, свойство Value возвращает значение Null, а свойство Text – пустую строку. Если выбрана строка в многостолбцовом списке, в свойства Value и Text будет записана информация из первого столбца.

Что делать, если понадобятся данные из других столбцов многостолбцового списка, кроме первого?

Для получения данных из любого столбца элемента управления ListBox используется свойство List, а для определения выбранной пользователем строки – ListIndex.

Для тестирования приведенного ниже кода скопируйте таблицу и вставьте ее в диапазон «A1:D4» на листе с ярлыком «Лист1»:

Звери Лев Тапир Вивера
Птицы Грач Сорока Филин
Рыбы Карась Налим Парусник
Насекомые Оса Жук Муравей

Создайте в редакторе VBA Excel пользовательскую форму и добавьте на нее список с именем ListBox1. Откройте модуль формы и вставьте в него следующие процедуры:

Private Sub UserForm_Initialize()

With Me.ListBox1

  ‘Указываем, что у нас 4 столбца

  .ColumnCount = 4

  ‘Задаем размеры столбцов

  .ColumnWidths = «50;50;50;50»

  ‘Импортируем данные

  .RowSource = «Лист1!A1:D4»

  ‘Привязываем список к ячейке «F1»

  .ControlSource = «F1»

End With

End Sub

Private Sub UserForm_Click()

MsgBox Me.ListBox1.List(Me.ListBox1.ListIndex, 2)

End Sub

В процедуре UserForm_Initialize() присваиваем значения некоторым свойствам элемента управления ListBox1 перед открытием пользовательской формы. Процедура UserForm_Click() при однократном клике по форме выводит в MsgBox значение из третьего столбца выделенной пользователем строки.

Результат извлечения данных из многостолбцового элемента управления ListBox

Теперь при выборе строки в списке, значение свойства Value будет записываться в ячейку «F1», а при клике по форме функция MsgBox выведет значение третьего столбца выделенной строки.

Обратите внимание, что при первом запуске формы, когда ячейка «F1» пуста и ни одна строка в ListBox не выбрана, клик по форме приведет к ошибке. Это произойдет из-за того, что свойство ListIndex возвратит значение -1, а это недопустимый номер строки для свойства List.

Если для списка разрешен многострочный выбор (MultiSelect = fmMultiSelectMulti или MultiSelect = fmMultiSelectExtended), тогда, независимо от количества выбранных строк, свойство Value будет возвращать значение Null, а свойство Text – пустую строку. Свойство ListIndex будет возвращать номер строки, которую кликнули последней, независимо от того, что это было – выбор или отмена выбора.

Иногда перед загрузкой в ListBox требуется отобрать уникальные элементы из имеющегося списка. Смотрите, как это сделать с помощью объектов Collection и Dictionary.

UserForm Controls — ComboBox and ListBox

———————————————————-

Contents:

Difference between ListBox and ComboBox

Key Properties of ComboBox and ListBox

Add Items/Data to (Populate) a ListBox or ComboBox

Extract ListBox & ComboBox Items, with VBA

Delete ListBox rows using the RemoveItem Method

———————————————————-

UserForm acts as a container in which you add multiple ActiveX controls, each of which has a specific use and associated properties. By itself, a UserForm will not be of much use unless ActiveX controls are added to it which are the actual user-interactive objects. Using ActiveX Controls on a Worksheet have been illustrated in detail, in the separate section of «Excel VBA: ActiveX Controls, Form Controls & AutoShapes on a Worksheet».

An Excel VBA ListBox or ComboBox is a list of items from which a user can select. They facilitate in accepting data from users and making entries in an Excel worksheet.

Difference between ListBox and ComboBox:

1. The ComboBox is a drop-down list (the user-entered item or the list-selected item is visible in the text area, whereas list values are visible by using the drop-down), while a ListBox shows a certain number of values with or without a scroll bar. In a ComboBox, only one row of items is visible at a given time (without using the drop-down) whereas in a ListBox one or more can be visible at a time.

2. In a ComboBox you can select ony one option from the list, while in a ListBox you can select multiple options from the list.

3. The user can enter his own item (in text area) in a ComboBox if it is not included in the list, which is not possible to do in a ListBox. In this sense, ComboBox is a combination of TextBox and ListBox.

4. CheckBox can be used within ListBox, but not within ComboBox. ListBox allows you to display a check box next to each item in the list, to enable user to select items (this might be easier for the user than using the multiple selection methods). To use CheckBoxes in a ListBox, set ListStyle property (in Properties Window)  to fmListStyleOption (vba code: ListBox1.ListStyle = fmListStyleOption). This setting is best used with a multiselect ListBox.

——————————————————————————————————————-

Key Properties of ComboBox and ListBox

Note1: All properties and methods given below are common to both ListBox and ComboBox, unless mentioned otherwise. Also refer «2. UserForm and Controls — Properties.» for properties common to the UserForm and most Controls.

Note 2: In below given examples, vba codes are required to be entered in the Code Module of the UserForm, unless specified otherwise.  

AddItem Method:

Adds an item to the list, in a single-column ListBox or ComboBox. Adds a row to the list (ie. an item for each row), in a multi-column ListBox or ComboBox. Syntax: Control.AddItem(Item, Index). Item specifies the item or row to add. Index is an Integer which specifies the position where the new item or row is placed within the list, and if omitted, the item or row is added at the end. The item or row numbers begin with zero, and the first item or row is numbered 0, and so on. The value of Index cannot be greater than the total number of rows (ie. value of ListCount property). AddItem method will not work if ComboBox or ListBox is bound to data, hence RowSource data should be cleared before use. AddItem method can only be used with a macro or vba code. Note: AddItem method adds an item to the first column in a multi-column ListBox or ComboBox, and to add an item further to the first column, use the List or Column property specifying the item’s row and column number. More than one row can also be added at a time to a ListBox or ComboBox by using the List or Column properties (AddItem adds one row at a time). This means that you can copy a two-dimensional array of values to a ListBox or ComboBox, using List or Column properties rather than adding each individual element using the AddItem method. Note: Using the Column property to copy a two-dimensional array of values to a ListBox or ComboBox, transposes the array contents and equates myArray(iRow, iColumn) to ListBox1.Column(iCol, iRow). List property copies an array without transposing it and myArray(iRow, iColumn) equates to ListBox1.List(iRow, iColumn). Refer Image 13 for example.

BoundColumn Property:

Specifies the column from which value is to be stored in a multicolumn ComboBox or ListBox, when a row is selected by the user. First column has a BoundColumn value of 1, second column has a value of 2, and so on. Setting the BoundColumn value to 1 will assign the value from column 1 to the ComboBox or ListBox, and so on. BoundColumn property lets the user to store a different set of values per specified column while TextColumn property displays one set of values, viz. use the Text property to return the value from the first column (specified in the TextColumn property) containing the names and the BoundColumn property can specify another column containing height wherein on selecting a particular person’s name in the ListBox, his height will get returned or stored (refer Image 10). The ColumnWidths property of a column can be set to zero to not display it in the ListBox. Setting the BoundColumn value to 0 assigns the value of the ListIndex property (which is the number of the selected row) as the value of the control (ComboBox or ListBox). This setting is useful if you want to determine the row of the selected item in a ComboBox or ListBox. BoundColumn Property can be set in the Properties window and can also be used with a macro or vba code. Note: Where the ControlSource mentions =Sheet3!D2 (vba code: .ControlSource = «=Sheet3!D2»), the value in the BoundColumn of the selected row will get stored in cell D2, Sheet3.

Example 1: Setting the BoundColumn value to 0 assigns the value of the ListIndex property (which is the number of the selected row) as the value of the control  (in a Single Selection ListBox) — refer Image 7

Private Sub UserForm_Initialize()
‘set ListBox properties on initialization of UserForm

With ListBox1

.ColumnHeads = True

.ColumnCount = 2

‘ColumnWidths property of the second column is set to zero to not display it in the ListBox.

.ColumnWidths = «50;0»

.RowSource = «=Sheet3!A2:B6»

.MultiSelect = fmMultiSelectSingle

.BoundColumn = 0

End With

End Sub

Private Sub CommandButton1_Click()
‘BoundColumn value is set as 0 which assigns the value of the ListIndex property (which is the number of the selected row) as the value of the control. Note: MultiSelect Property is set to fmMultiSelectSingle which allows only single selection.

If ListBox1.Value <> «» Then

TextBox1.Value = ListBox1.Value + 2

End If

End Sub

Clear Method:

Removes all items in a ComboBox or ListBox. Syntax: Control.Clear. Clear method will not work if ComboBox or ListBox is bound to data, hence RowSource data should be cleared before use. Clear method can only be used with a macro or vba code. 

Column Property:

Refers to a specific column, or column and row combination, in a multiple-column ComboBox or ListBox. Syntax: Control.Column(iColumn, iRow). Column property can only be used with a macro or vba code and is not available at design time. iColumn specifies the column number wherein iColumn = 0 means the first column in the List. iRow specifies the row number wherein iRow = 0 means the first row in the List. Both iColumn and iRow are integer values ranging from 0 to number of columns and rows (respectively) in the list minus 1. Specifying both column and row numbers will refer to a specific item, and specifying only the column number will refer to a specific column in the current row viz. ListBox1.Column(1) refers the second column. You can copy a two-dimensional array of values to a ListBox or ComboBox, using Column (or List) property rather than adding each individual element using the AddItem method. Column property can be used to assign the contents of a ComboBox or ListBox to another control, viz. TextBox (refer Image 8). Note: Using the Column property to copy a two-dimensional array of values to a ListBox or ComboBox, transposes the array contents and equates myArray(iRow, iColumn) to ListBox1.Column(iCol, iRow). List property copies an array without transposing it and myArray(iRow, iColumn) equates to ListBox1.List(iRow, iColumn). Refer Image 13 for example.

Example 2: Load ListBox using AddItem method and List & Column properties; and use Column property to assign the contents of ListBox to TextBox — refer Image 8

Private Sub UserForm_Initialize()
‘set ListBox properties on initialization of UserForm

With ListBox1

.ColumnCount = 3

.ColumnWidths = «50;50;50»

.ColumnHeads = False

.RowSource = «=Sheet2!A2:B6»

.MultiSelect = fmMultiSelectMulti

End With

‘clearing the TextBox if it is not empty
TextBox1 = «»

End Sub

Private Sub CommandButton1_Click()
‘Add items in ListBox using AddItem method to add new rows; use List & Column properties to add items in columns beyond the first column; and use Column property to assign the contents of ListBox to TextBox

‘AddItem method will not work if ListBox is bound to data, hence RowSource is cleared if it had been set
ListBox1.RowSource = «»

‘Create a new row with AddItem 

ListBox1.AddItem «banana»
‘add item in second column of this first row, using List property
ListBox1.List(0, 1) = «tuesday»
‘adding items in the 3 columns of the first row — this will become the second row in the end
ListBox1.List(0, 2) = «day 2»

ListBox1.AddItem «orange»

‘add item in second column of this second row, using Column property
ListBox1.Column(1, 1) = «wednesday»
‘adding items in the 3 columns of the second row — this will become the third row in the end
ListBox1.Column(2, 1) = «day 3»

‘Create a new row with AddItem and position as row number 1
ListBox1.AddItem «apple», 0

ListBox1.List(0, 1) = «monday»

‘adding items in the 3 columns and positioning this row as the first row — this will push down the above two rows
ListBox1.List(0, 2) = «day 1»

‘item in column number 3 and row number 2 of ListBox
TextBox1.Value = ListBox1.Column(2, 1)

End Sub

ColumnCount Property:

Specifies the number of columns to be displayed in a ComboBox or ListBox. A ColumnCount value of 0 does not display any column and a setting of -1 displays all columns. ColumnCount property can be set in the Properties window and can also be used with a macro or vba code.

ColumnHeads Property:

A Boolean value (True/False) which determines display of column headings (in a single row) for ComboBox or ListBox. ColumnHeads property can be set in the Properties window and can also be used with a macro or vba code. Column Headings can be displayed only if ColumnHeads is set to True in Properties window (VBA code: ListBox1.ColumnHeads = True) and if you bind the ListBox to a range (ie. set RowSource to a range that includes headings). Note: AddItem method will not work if ListBox or ComboBox is bound to data, hence RowSource property should be cleared for using AddItem.

List Property:

List Property is used in conjunction with the ListCount and ListIndex properties to return items in a ListBox or ComboBox control. Syntax -> Control.List(iRow,iCol). Each item in a list has a row number and a column number, wherein row and column numbers start with zero. iRow specifies the row number wherein iRow = 2 means the third row in the List. iColumn specifies the column number wherein iColumn = 0 means the first column in the List. Omitting to specify the iColumn will retrieve the first column. Specify iColumn only for a multi-column ListBox or ComboBox. List Property can only be used with a macro or vba code and is not available at design time. Note: To copy a two-dimensional array of values to a ListBox or ComboBox, use List or Column properties. To add a one-dimensional array or to add an individual element, use the AddItem method. Items can be removed from a List using the RemoveItem method. List property is available only by using a macro or VBA.

Example 3: Use Selected & List properties to display multiple-selected ListBox items (choose any column to display) in TextBox, and link a worksheet cell with TextBox using ControlSource property — refer Image 9. 

Private Sub UserForm_Initialize()
‘set ListBox properties on initialization of UserForm

With ListBox1

.ColumnHeads = True

.ColumnCount = 2

‘ColumnWidths property of the second column is set to zero to not display it in the ListBox.

.ColumnWidths = «50;0»

.RowSource = «=Sheet3!A2:B6»

.MultiSelect = fmMultiSelectMulti

.TextColumn = 1

End With

With TextBox1

.MultiLine = True

‘the text or value in the TextBox will get stored in the worksheet cell — Sheet3!F2
.ControlSource = «=Sheet3!F2»
‘if the cell Sheet3!F2 contains any text, this will not appear in the TextBox on initialization of UserForm
.Value = «»

End With

End Sub

Private Sub CommandButton1_Click()
‘Use Selected & List properties to display multiple-selected ListBox items (choose any column to display) in TextBox, and link a worksheet cell with TextBox using ControlSource property

TextBox1.Value = «»

‘check all items in a ListBox
For n = 0 To ListBox1.ListCount — 1

‘if a ListBox item is selected, it will display in TextBox
If ListBox1.Selected(n) = True Then

If TextBox1.Value = «» Then

‘ListBox1.List(n, 0) or ListBox1.List(n)displays the first column in TextBox, ListBox1.List(n, 1) displays the second column and so on
‘alternate code which displays the second column in TextBox: TextBox1.Value = Range(ListBox1.RowSource).Offset(n, 1).Resize(1, 1).Value
TextBox1.Value = ListBox1.List(n, 1)

Else

‘alternate code which displays the second column in TextBox: TextBox1.Value = TextBox1.Value & vbCrLf & Range(ListBox1.RowSource).Offset(n, 1).Resize(1, 1).Value

TextBox1.Value = TextBox1.Value & vbCrLf & ListBox1.List(n, 1)

End If

End If

Next n

End Sub

ListCount Property:

Determines the total number of rows in a ListBox or ComboBox. This property can only be used with a macro or vba code and is not available at design time. Note: The column headings row is also counted, if ColumnHeads are displayed. The ListCount property can be used with the ListRows property to specify the number of rows to display in a ComboBox.

ListIndex Property:

Determines which item is selected in a ComboBox or ListBox. The first item in a list has a ListIndex value of 0, the second item has a value of 1, and so on. Hence, it is an integer value ranging from 0 to the total number of items in a ComboBox or ListBox minus 1. ListIndex returns -1 when no rows are selected. This property can only be used with a macro or vba code and is not available at design time. Note: In a Multiple Selection enabled ListBox, ListIndex returns the index of the row that has focus, irrespective of whether that row is selected or not. Hence the Selected property of the ListBox (and not the ListIndex property) shoud be used here to return and set a selection. In a Single Selection enabled ListBox (viz. MultiSelect property setting of fmMultiSelectSingle), ListIndex returns the index of the selected item and hence ListIndex property should be used here to return and set a selection.

ListRows Property:

Specifies the maximum number of rows which will display in the list box portion of a ComboBox. The default value is 8. Note: If the actual number of list items exceed this maximum value of the ListRows property, a vertical scroll bar will appear in the list box portion of the ComboBox (and the excess list items can be viewed by scrolling down). The ListCount property can be used with the ListRows property to specify the number of rows to display in a ComboBox. ListRows property can be set in the Properties window and can also be used with a macro or vba code. ListRows Property is valid for ComboBox and not for ListBox.

Example 4: Using the ListCount property with the ListRows property, to set number of rows to display in ComboBox

Private Sub UserForm_Initialize()
‘this macro sets the ListRow value, on initialization of the UserForm

With ComboBox1

If .ListCount > 5 Then

.ListRows = 5

Else

.ListRows = .ListCount

End If

End With

End Sub

MultiSelect Property:

Specifies whether multiple selections are allowed. There are 3 settings: (i) fmMultiSelectSingle (value 0), the default setting, wherein only a single item can be selected; (ii) fmMultiSelectMulti (value 1) which allows multiple selections wherein an item can be selected or deselected by clicking mouse or pressing SPACEBAR; and (iii) fmMultiSelectExtended (value 2) which allows multiple selections, wherein by pressing SHIFT and simultaneously moving the up or down arrows (or pressing SHIFT and clicking mouse) continues selection from the previously selected item to the current selection (ie. a continuous selection); this option also allows to select or deselect an item by pressing CTRL and clicking mouse. MultiSelect property can be set in the Properties window and can also be used with a macro or vba code. Note: MultiSelect Property is valid for ListBox and not for ComboBox. When multiple selections are made (viz. fmMultiSelectMulti or fmMultiSelectExtended), the selected items can be determined only by using the Selected property (Selected property is available by using macro) of the ListBox. The Selected property will have values ranging from 0 to ListCount minus 1 and will be True if the item is selected and False if not selected. The Selected property determines the items you chose, and the List property returns the items.

Example 5: Determining selected item in a Single Selection ListBox, in VBA:

Private Sub CommandButton1_Click()
‘determine and display selected item in a ListBox which allows only a single selection (viz. MultiSelect Property is set to fmMultiSelectSingle)
‘you can also determine selected item in a ListBox which allows only a single selection, by using the Selected Property (as used in a Multiple Selection enabled ListBox)

‘alternatively: If ListBox1.ListIndex >= 0 Then
If ListBox1.Value <> «» Then

MsgBox ListBox1.Value

End If

End Sub

RemoveItem Method:

A specified row is removed from the list in a ComboBox or ListBox. Syntax: Control.RemoveItem(Row_Index). Row_Index is the row number which is specified to be removed, wherein the first row is numbered 0, and so on. RemoveItem method will not work if ComboBox or ListBox is bound to data, hence RowSource data should be cleared before use. RemoveItem method can only be used with a macro or vba code.

RowSource Property:

Specifies the source of a list (which could be a worksheet range in Excel), for a ComboBox or ListBox. RowSource property can be set in the Properties window and can also be used with a macro or vba code. To set RowSource property in Properties window, enter without inverted commas: «=Sheet2!A2:A6» which populates ComboBox or ListBox with values in cells A2:A6 in Sheet2. VBA code for this is: ListBox1.RowSource = «=Sheet2!A2:A6». It is not necessary to use the equal mark in «=Sheet2!A2:A6» while setting the property and ListBox1.RowSource = «Sheet2!A2:A6» will have the same effect.

Selected Property:

Specifies whether an item is selected in a ListBox control. Syntax: Control.Selected(Item_Index). Returns True/False if the item is Selected/NotSelected; Set to True/False to select the item or remove selection [viz. Control.Selected(ItemIndex) = True/False]. Item_Index is an integer value ranging from 0 to number of items in the list minus 1, indicating its relative position in the list, viz. ListBox.Selected(2) = True selects the third item in the list. Selected property is particularly useful when working with multiple selections. Selected Property can only be used with a macro or vba code and is not available at design time. Note1: In a Multiple Selection enabled ListBox, ListIndex returns the index of the row that has focus, irrespective of whether that row is selected or not. Hence the Selected property of the ListBox (and not the ListIndex property) shoud be used here to return and set a selection. In a Single Selection enabled ListBox (viz. MultiSelect property setting of fmMultiSelectSingle), ListIndex returns the index of the selected item and hence ListIndex property should be used here to return and set a selection. Note2: Selected Property is valid for ListBox and not for ComboBox.

Example 6: Determining selected items in a multiple-selection enabled ListBox using Selected & List properties:

Private Sub CommandButton1_Click()
‘display all selected items in a ListBox using the Selected property (valid for a ListBox with MultiSelect Property setting of either single-selection or multiple-selection)

‘check all items in a ListBox
For n = 0 To ListBox1.ListCount — 1

‘if a ListBox item is selected, it will display in MsgBox

If ListBox1.Selected(n) = True Then

‘display a selected item
MsgBox ListBox1.List(n)

End If

Next n

End Sub

Style Property:

Valid for ComboBox only, not for ListBox. This property determines choosing or setting the value of ComboBox. There are 2 settings: (i) fmStyleDropDownCombo (value 0). The user has both options of typing a custom value in the text area or select from the drop-down list. This is the default value.; (ii) fmStyleDropDownList (value 2). The user can only select from the drop-down list, like in ListBox. Style Property can be set in the Properties window and can also be used with a macro or vba code.

TextColumn Property:

Specifies the column of data in a ListBox that supplies data for its Text property — the TextColumn property determines the column whose value the Text property will return whereas the BoundColumn property determines the column whose value the Value property returns. The Text property returns the same as Value property if the TextColumn property is not set. First column has a TextColumn value of 1, second column has a value of 2, and so on. Setting the TextColumn value to -1 indicates that the first column with a ColumnWidths value greater than 0 will be displayed. TextColumn property enables display of one set of values to the user but store a different set of values (per column specified in the BoundColumn property) viz. use the Text property to return the value from the first column (specified in the TextColumn property) containing the names and the BoundColumn property can specify another column containing height wherein on selecting a particular person’s name in the ListBox, his name & height will be returned. The ColumnWidths property of any column can be set to zero to not display it in the ListBox. Setting the TextColumn value to 0 displays the ListIndex value (which is the number of the selected row) in TextColumn Property — this setting is useful if you want to determine the row of the selected item. TextColumn property can be set in the Properties window and can also be used with a macro or vba code. Note: In a ComboBox, when a user selects an item, the column specified in the TextColumn property will be displayed in the ComboBox’s text box portion.

Example 7: Display first column in the List and use the TextColumn & BoundColumn Properties to return values from first & third columns (in a Single Selection ListBox) — refer Image 10

Private Sub UserForm_Initialize()
‘set ListBox properties on initialization of UserForm

With ListBox1

.ColumnHeads = True

.ColumnCount = 3

‘set the ColumnWidths property of second & third columns to zero to not display them in the ListBox

.ColumnWidths = «40;0:0»

.RowSource = «=Sheet2!A2:C6»

.MultiSelect = fmMultiSelectSingle

‘specifies the column of data in a ListBox that supplies data for its Text property

.TextColumn = 1

.BoundColumn = 3

End With

End Sub

Private Sub CommandButton1_Click()
‘TextColumn value is set as 1 and BoundColumn value is set as 3.

‘works only if MultiSelect Property of ListBox is set to fmMultiSelectSingle which allows single selection.
If ListBox1.Value <> «» Then   

‘use the ListBox Text property to return the value from the column specified in the TextColumn column, whereas the ListBox Value property returns the value from the column specified in the BoundColumn property

TextBox1.Value = ListBox1.Text & » — » & ListBox1.Value & » cms»

End If

End Sub

———————————————————————————————————————  

Add Items/Data to (Populate) a ListBox or ComboBox

1. Setting the RowSource property of a ListBox or ComboBox in a UserForm

VBA code — if the list is static:

Me.ListBox1.RowSource = «Sheet1!A1:B6»

or
Me.ListBox1.RowSource = «=Sheet1!A1:B6»

VBA code — if the list is dynamic:

Me.ListBox1.RowSource = «Sheet1!A1:B» & Sheet1.Cells(Rows.Count, «B»).End(xlUp).Row

Note: You can set the RowSource property of a ListBox or ComboBox in the Properties Window (without using vba code), by entering -> Sheet1!A1:B6

Example 8: Populate ComboBox by setting the RowSource property to a named list — refer Image 11

Private Sub UserForm_Initialize()
‘populate ComboBox by setting the RowSource property to a named list

With ComboBox1

.ColumnCount = 2

.ColumnWidths = «50;50»

.ColumnHeads = True

‘For a named list (viz. “HeightList” in Range A2:B6), the RowSource property can be set to Sheet1!HeightList

.RowSource = «Sheet1!HeightList»

End With

End Sub

2. Populate a ComboBox or ListBox from an Array:

VBA code — populate single column in ListBox:

ListBox1.List = Array(«RowOne», «RowTwo», «RowThree», «RowFour»)

VBA code — populate single column in ComboBox:

ComboBox1.List = Array(«Apples», «Bananas», «Oranges», «Pears»)

VBA code — populate ListBox from array named myArray:

Dim myArray As Variant
myArray = Array(«Adidas», «Nike», «Reebok»)
Me.ListBox1.List = myArray

VBA code — Populate single column ComboBox:

Dim i As Integer
Dim myArray As Variant

myArray = Array(«Adidas», «Nike», «Reebok», «Puma», «Polo»)

    For i = LBound(myArray) To UBound(myArray)

Me.ComboBox1.AddItem myArray(i)

Next

Example 9 — Populate a multi-column Listbox directly with Worksheet Range — multiple rows added at one time using the List property:

Private Sub UserForm_Initialize()
‘set ListBox properties on initialization of UserForm

With ListBox1

.ColumnCount = 3

.ColumnWidths = «50;50;50»

.ColumnHeads = False

End With

‘Load Worksheet Range directly to a ListBox

Dim rng As Range

Set rng = Sheet1.Range(«A1:C6»)

Me.ListBox1.List = rng.Cells.Value

End Sub

Example 10 — Populate a multi-column Listbox directly with Worksheet Range — multiple rows added at one time using the List property:

Private Sub UserForm_Initialize()
‘set ListBox properties on initialization of UserForm

With ListBox1

.ColumnCount = 3

.ColumnWidths = «50;50;50»

.ColumnHeads = False

End With

‘Load Worksheet Range directly to a ListBox:

Dim var As Variant

var = Sheet1.Range(«A1:C6»)

Me.ListBox1.List = var

End Sub

Example 11: Load Worksheet Range to a multi-column ListBox, after placing Range data in a 2-dimensional Array — refer Image 12

Option Base 1
——————————————
Private Sub UserForm_Initialize()
‘Load Worksheet Range to a ListBox, after placing data in an Array

Dim rng As Range
Dim cell As Range
Dim totalRows As Integer, totalColumns As Integer
Dim iRow As Integer, iCol As Integer
Dim myArray() As Variant

Set rng = Sheet1.Range(«A1:C6»)
totalRows = Sheet1.Range(«A1:C6»).Rows.Count
totalColumns = Sheet1.Range(«A1:C6»).Columns.Count

‘if Option Base 1 was not set, this line of code should be: ReDim myArray(1 To totalRows, 1 To totalColumns)
ReDim myArray(totalRows, totalColumns)

‘place worksheet range data in an Array:
For Each cell In rng

For iRow = 1 To totalRows

For iCol = 1 To totalColumns

myArray(iRow, iCol) = rng.Cells(iRow, iCol)

Next iCol

Next iRow

Next

‘set ListBox properties and load Array to ListBox

With ListBox1

.ColumnCount = 3

.ColumnWidths = «50;50;50»

.ColumnHeads = False

.List = myArray

End With

End Sub

Example 12: Load a 2-dimensional array to ListBox using the List property (copies an array without transposing it) and Column property (which transposes the contents of the array) — refer Image 13

Private Sub UserForm_Initialize()
‘set ListBox properties on initialization of UserForm

With ListBox1

.ColumnCount = 3

.ColumnWidths = «50;50;50»

.ColumnHeads = False

End With

With ListBox2

.ColumnCount = 3

.ColumnWidths = «50;50;50»

.ColumnHeads = False

End With

End Sub

Private Sub CommandButton1_Click()
‘create a 2-dimensional array and load to ListBox using the List property (copies an array without transposing it) and Column property (which transposes the contents of the array)

‘Declaring the array and its dimensions. The array has been named myArray, of size 3 by 3 (three rows by three columns). Note: When you populate an array with data, the array will start at zero, and if you include Option Base 1 the array will start at 1.
Dim myArray(3, 3)

‘populate column 1 of myArray, with numbers

For n = 0 To 2

myArray(n, 0) = n + 1

Next n

‘populate column 2 of myArray
myArray(0, 1) = «R1C2»
myArray(1, 1) = «R2C2»
myArray(2, 1) = «R3C2»

‘populate column 3 of myArray
myArray(0, 2) = «R1C3»
myArray(1, 2) = «R2C3»
myArray(2, 2) = «R3C3»

‘copy data to ListBox1 (using List property) and ListBox2 (using Column property):

‘copies an array without transposing it
ListBox1.List() = myArray
‘transposes the contents of the array
ListBox2.Column() = myArray

End Sub

3. Populate a ComboBox or ListBox with AddItem method

Example 13: Populate a single-column ListBox from worksheet range

Private Sub UserForm_Initialize()
‘set ListBox properties on initialization of UserForm

With ListBox1

.ColumnCount = 1

.ColumnWidths = «50»

.ColumnHeads = False

‘AddItem method will not work if ListBox is bound to data, hence RowSource is cleared if it had been set

.RowSource = «»

End With

‘populating a single-column ListBox with AddItem method
Dim cell As Range
Dim rng As Range

    
Set rng = Sheet1.Range(«A1:A6»)

For Each cell In rng.Cells

Me.ListBox1.AddItem cell.Value

Next cell

End Sub

Example 14: Populate a single-column ListBox with values from 1 to 500

Private Sub UserForm_Initialize()
‘set ListBox properties on activation of UserForm

With ListBox1

.ColumnCount = 1

.ColumnWidths = «50»

‘AddItem method will not work if ListBox is bound to data, hence RowSource is cleared if it had been set

.RowSource = «»

End With

‘populate a single-column ListBox with values from 1 to 500, and «N/A»
With ListBox1

.AddItem «N/A»

For i = 1 To 500

.AddItem i

Next i

End With

End Sub

Example 15: Create a new row with AddItem and specify its row number — refer Image 14

Private Sub UserForm_Initialize()
‘set ListBox properties on initialization of UserForm

With ListBox1

.ColumnCount = 1

.ColumnWidths = «50»

.ColumnHeads = False

‘AddItem method will not work if ListBox is bound to data, hence RowSource is cleared if it had been set

.RowSource = «»

End With

‘using AddItem method to populate single-column ListBox:
ListBox1.AddItem «banana»
ListBox1.AddItem «orange»

‘Create a new row with AddItem and position as row number 1 — this will push down the above two rows
ListBox1.AddItem «apple», 0
‘Create a new row with AddItem and position as row number 2 — this will push down the above two rows to no. 3 and 4
ListBox1.AddItem «pears», 1

End Sub

Example 16: Populate a ComboBox with the 12 months in a year — Refer Image 15

Private Sub UserForm_Initialize()
‘set ComboBox properties on initialization of UserForm

With ComboBox1

.ColumnCount = 1

.ColumnWidths = «50»

.ColumnHeads = False

‘AddItem method will not work if ComboBox is bound to data, hence RowSource is cleared if it had been set

.RowSource = «»

End With

‘populates ComboBox with the 12 months in a year

For n = 1 To 12

ComboBox1.AddItem Format(DateSerial(2011, n, 1), «mmmm»)

Next n

End Sub

4. Populate a multi-column ComboBox or ListBox using AddItem method and List & Column properties

Example 17:  refer Image 16

Private Sub UserForm_Initialize()
‘set ComboBox properties on initialization of UserForm

With ComboBox1

.ColumnCount = 3

.ColumnWidths = «50;50;50»

.ColumnHeads = False

‘AddItem method will not work if ComboBox is bound to data, hence RowSource is cleared if it had been set

.RowSource = «»

End With

‘Populating a multi-column ListBox using AddItem method and List & Column properties:

‘Create a new row with Additem
ComboBox1.AddItem «banana»
‘add item in second column of this first row, using List property
ComboBox1.List(0, 1) = «tuesday»
‘adding items in the 3 columns of the first row — this will become the second row in the end
ComboBox1.List(0, 2) = «day 2»

ComboBox1.AddItem «orange»

‘add item in second column of this second row, using Column property
ComboBox1.Column(1, 1) = «wednesday»
‘adding items in the 3 columns of the second row — this will become the third row in the end
ComboBox1.Column(2, 1) = «day 3»

‘Create a new row with Additem and position as row number 1
ComboBox1.AddItem «apple», 0
ComboBox1.List(0, 1) = «monday»

‘adding items in the 3 columns and positioning this row as the first row — this will push down the above two rows
ComboBox1.List(0, 2) = «day 1»

End Sub

5. Populate a multi-column ListBox from a worskheet range, using AddItem method and List property

Example 18:  refer Image 17

Private Sub UserForm_Initialize()
‘set ListBox properties on initialization of UserForm

With ListBox1

.ColumnCount = 3

.ColumnWidths = «50;50;50»

‘AddItem method will not work if ListBox is bound to data, hence RowSource is cleared if it had been set

.RowSource = «»

End With

End Sub

Private Sub CommandButton1_Click()
‘populate a multi-column ListBox from a worskheet range, using AddItem method and List property

Dim counter As Long
Dim totalRows As Long

‘determine total number of rows in column A
totalRows = Sheet4.Cells(Rows.Count, «A»).End(xlUp).Row
counter = 0

‘ListBox gets populated with all rows in column A:
Do

With Me.ListBox1

counter = counter + 1

‘create a new row with Additem
.AddItem Sheet4.Cells(counter, 1).Value
‘add item in second column of a row
.List(.ListCount — 1, 1) = Sheet4.Cells(counter, 1).Offset(0, 1).Value
‘add item in third column of a row

.List(.ListCount — 1, 2) = Sheet4.Cells(counter, 1).Offset(0, 2).Value

End With

Loop Until counter = totalRows

End Sub

6. Add a new item/row to the list if ComboBox is bound to data in a worksheet. 

Example 19: refer Images 18a & 18b

Private Sub UserForm_Initialize()
‘set ComboBox properties on initialization of UserForm

With ComboBox1

.ColumnCount = 3

.ColumnWidths = «50;50;50»

.ColumnHeads = True

.BoundColumn = 1

‘a named-range (name: «cbRange») has been created in Sheet3 of the workbook, using the Name Manager: «=Sheet3!$A$2:$C$6»

.RowSource = «cbRange»

End With

End Sub

Private Sub CommandButton1_Click()
‘add a new item/row to the list if ComboBox is bound to data in a worksheet

Dim colNo As Long

‘determine first column of the named-range «cbRange»
colNo = Range(«cbRange»).Column

‘create a new single-column named-range (name: «cbRangeTemp»), populated with only the first column of the named-range «cbRange».
Range(«cbRange»).Resize(Range(«cbRange»).Rows.Count, 1).Name = «cbRangeTemp»

‘checks if ComboBox1.Value is already existing in column 1 of named-range «cbRange»
If Application.CountIf(Range(«cbRangeTemp»), ComboBox1.Value) = 0 Then

‘resizing the named-range «cbRange», to add another worksheet row at the end, wherein the ComboBox1.Value will get posted:

Range(«cbRange»).Resize(Range(«cbRange»).Rows.Count + 1).Name = «cbRange»

ComboBox1.RowSource = «cbRange»

‘posting columns of the new row with values from ComboBox1, TextBox1 & TextBox2:

Sheet3.Cells(Range(«cbRange»).Rows.Count + 1, colNo) = ComboBox1.Value

Sheet3.Cells(Range(«cbRange»).Rows.Count + 1, colNo).Offset(0, 1) = TextBox1.Text

Sheet3.Cells(Range(«cbRange»).Rows.Count + 1, colNo).Offset(0, 2) = TextBox2.Text

Else

MsgBox «Item already in List»

End If

ComboBox1.Value = «»
TextBox1.Text = «»
TextBox2.Text = «»

End Sub

——————————————————————————————————————————————-  

Extract ListBox & ComboBox Items, with VBA

VBA code — Display selected ComboBox item in TextBox:

‘the text area of ComboBox shows the item entered by user of his own choice or that selected from list items, and this item gets displayed in TextBox

TextBox1.Value = ComboBox1.Value

Note: VBA code-> TextBox1.Value = ListBox1.Value, or TextBox1.Text = ListBox1.Value, will work only in case MultiSelect property of ListBox is set to fmMultiSelectSingle, ie. in case of a single-selection enabled ListBox. It will copy the selected item (value in BoundColumn) from the list.

VBA code — Copy selected ComboBox item to a worksheet range:

‘the text area of ComboBox shows the item entered by user of his own choice or that selected from list items, and this item is copied to the worksheet range

Sheet1.Range(«G4»).Value = ComboBox1.Value

Note: VBA code-> Sheet4.Range(«G4»).Value = ListBox1.Value, will work only in case MultiSelect property of ListBox is set to fmMultiSelectSingle, ie. in case of a single-selection enabled ListBox. It will copy the selected item (value in BoundColumn) from the list.

VBA code — Copy ComboBox item determined by its position, to a worksheet range:

‘an existing ComboBox item, determined by its position (row 4, column 1), posted to a worksheet cell

Sheet1.Range(«F2»).Value = ComboBox1.List(3, 0)

Note: VBA code for ListBox -> Sheet1.Range(«F2»).Value = ListBox1.List(3, 0)

Example 20: Extracting ListBox items (of multi-column ListBox) to a worksheet range — refer Image 19

Private Sub UserForm_Initialize()
‘set ListBox properties on initialization of UserForm

With ListBox1

.ColumnCount = 3

.ColumnWidths = «50;50;50»

.ColumnHeads = True

.RowSource = «Sheet2!A2:C6»

.MultiSelect = fmMultiSelectMulti

End With

End Sub

Private Sub CommandButton1_Click()
‘Use Selected & List properties to copy multiple-selected ListBox items (of multi-column ListBox) to a worksheet range

‘check all items/rows in a ListBox
For r = 0 To ListBox1.ListCount — 1

‘if a ListBox row is selected, it will get copied to the worksheet range

If ListBox1.Selected(r) = True Then

‘copying multi-column ListBox rows to corresponding/matching worksheet rows & columns:

For c = 1 To ListBox1.ColumnCount

Sheet1.Cells(r + 1, c).Value = ListBox1.List(r, c — 1)

Next c

End If

Next r

End Sub

Example 21: Extract multiple items in a row from a single-selection enabled & multi-column ListBox, and copy to worksheet range — refer Image 20

Private Sub UserForm_Initialize()
‘set ListBoxBox properties on initialization of UserForm

With ListBox1

.ColumnCount = 3

.ColumnWidths = «50;50;50»

.ColumnHeads = True

.BoundColumn = 1

.MultiSelect = fmMultiSelectSingle

.RowSource = «Sheet3!A2:C6»

End With

End Sub

Private Sub CommandButton1_Click()
‘extract multiple items in a row from a single-selection enabled & multi-column ListBox, and copy to worksheet range
‘ListIndex property is used to return and set a selection in a single-selection ListBox, but not in a multi-selection ListBox
‘ListBox1.Value will work only in case of a single-selection ListBox. It will copy the selected item (value in BoundColumn) from the list.

Dim rng As Range
Set rng = Sheet3.Cells(9, 1)

    
If ListBox1.Value <> «» Then

rng.Value = ListBox1.Value

rng.Offset(0, 1).Value = ListBox1.List(ListBox1.ListIndex, 1)

rng.Offset(0, 2).Value = ListBox1.List(ListBox1.ListIndex, 2)

End If

    
End Sub

Example 22: Select or enter name in ComboBox, and lookup its corresponding Grade in a worksheet range — refer Image 21

Private Sub UserForm_Initialize()
‘set comboBox properties on initialization of UserForm

With ComboBox1

.ColumnCount = 1

.ColumnWidths = «50»

.ColumnHeads = True

.RowSource = «Sheet3!A2:B6»

End With

‘disallow manual entry in TextBox

With TextBox1

.Enabled = False

End With

End Sub

Private Sub CommandButton1_Click()
‘select or enter name in ComboBox, and lookup its corresponding Grade in a worksheet range — use ComboBox, TextBox & CheckBox properties and worksheet functions Vlookup and Countif

Dim totalRows As Long

‘determine total number of rows in column B
totalRows = Sheet3.Cells(Rows.Count, «B»).End(xlUp).Row

Me.ComboBox1.ControlTipText = «Select Name»
Me.CommandButton1.ControlTipText = «Click to get Grade»

‘Name selected in ComboBox is posted to TextBox
TextBox1.Text = ComboBox1.Value

‘Grade will be searched only if a name is selected and the CheckBox is selected:
If CheckBox1 = True And TextBox1.Text <> «» Then

‘check if name selected or entered in ComboBox is present in the lookup range:

If Application.CountIf(Sheet3.Range(«A1:A» & totalRows), TextBox1.Text) > 0 Then

‘lookup Grade of selected Name, in the worksheet range

Sheet3.Cells(1, 4).Value = TextBox1.Text & «‘s grade is » & Application.VLookup(TextBox1.Text, Sheet3.Range(«A1:B» & totalRows), 2, False)

Else

MsgBox «Name not found!»

End If

End If

End Sub

——————————————————————————————————————————————-  

Delete ListBox rows using the RemoveItem Method

Example 23: Use RemoveItem method to delete a ListBox row. The below code deletes the row from the ListBox and also deletes the row items (or rows) in the worksheet — refer Images 22a and 22b.

Private Sub UserForm_Initialize()
‘set ListBox properties on initialization of UserForm

With ListBox1

.ColumnCount = 3

.ColumnWidths = «50;50;50»

.ColumnHeads = False

.MultiSelect = fmMultiSelectMulti

End With

Dim totalRows As Long

‘determine total number of rows in column A
totalRows = Sheet3.Cells(Rows.Count, «A»).End(xlUp).Row

‘load a dynamic worksheet range to a ListBox
Dim rng As Range
Set rng = Sheet3.Range(«A2:C» & totalRows)
Me.ListBox1.List = rng.Cells.Value

‘removes all items in ListBox
‘ListBox1.Clear

End Sub

Private Sub CommandButton1_Click()
‘use RemoveItem method to delete a ListBox row. The below code deletes the row from the ListBox and also deletes the row items (or rows) in the worksheet

Dim n As Long, i As Long
Dim var As Variant

‘deleting row from ListBox using RemoveItem method:

‘check all items in a ListBox; reverse order (Step -1) is used because rows are being deleted from ListBox.
For n = ListBox1.ListCount — 1 To 0 Step -1

If ListBox1.Selected(n) = True Then

‘item to be deleted is stored in the variable named var

var = ListBox1.List(n, 0)
ListBox1.RemoveItem (n)

‘determine row number in which items are to be deleted; Note: value of variable named var is derived from first column, hence Range(«A:A») is searched in the Match formula.
i = Application.Match(var, Sheet3.Range(«A:A»), 0)

‘delete all 3 columns of the determined row in the worksheet:
Sheet3.Cells(i, 1) = «»

Sheet3.Cells(i, 1).Offset(0, 1) = «»
Sheet3.Cells(i, 1).Offset(0, 2) = «»

‘use this code instead of the preceding 3-lines, to delete the determined row in the worksheet
‘Sheet3.Rows(i).Delete

End If

Next n

End Sub

Example 24: Delete all rows in ListBox, using RemoveItem method

Private Sub UserForm_Initialize()
‘set ListBoxBox properties on initialization of UserForm

With ListBox1

.ColumnCount = 3

.ColumnWidths = «50;50;50»

.BoundColumn = 1

.MultiSelect = fmMultiSelectMulti

‘RemoveItem method will not work if ListBox is bound to data, hence RowSource is cleared if it had been set

ListBox1.RowSource = «»

End With

For n = 2 To 6

With Me.ListBox1

‘create a new row with Additem

.AddItem Sheet3.Cells(n, 1).Value
‘add item in second column of a row

.List(.ListCount — 1, 1) = Sheet3.Cells(n, 1).Offset(0, 1).Value
‘add item in third column of a row

.List(.ListCount — 1, 2) = Sheet3.Cells(n, 1).Offset(0, 2).Value

End With

Next n

End Sub

Private Sub CommandButton1_Click()
‘delete all rows in ListBox, using RemoveItem method

Dim n As Integer

For n = 1 To ListBox1.ListCount

‘Note: «ListBox1.RemoveItem 0» is the same as «ListBox1.RemoveItem (0)»

‘alternate code: ListBox1.RemoveItem 0

ListBox1.RemoveItem ListBox1.ListCount — 1

Next n

End Sub

Понравилась статья? Поделить с друзьями:
  • Vba excel sql connect
  • Vba excel project locked
  • Vba excel split что это
  • Vba excel rgb colors
  • Vba excel private sub что это