简体   繁体   中英

Clearing ComboBox on Workbook_Open

I have following code in the Workbook_Open event handler:

   Sheet1.ComboBox1.Clear
   Sheet1.ComboBox2.Clear

   Set Rng = Sheet2.Range("A3", Sheet2.Cells(Rows.Count, "A").End(xlUp))
   With CreateObject("Scripting.Dictionary")
   For Each cel In Rng
   If Not .exists(cel.Value) Then
        .Add cel.Value, Nothing
    End If

 Sheet1.ComboBox1.List = .keys

My issue is that it is not clearing ComboBox1 on Workbook_Open and shows earlier selected values.

I also used following

     Sheet1.ComboBox1.ListIndex = -1 ' instead of sheet1.combobox1.clear
     Sheet1.ComboBox2.ListIndex = -1 ' instead of sheet1.combobox2.clear

But the problem remains.

Can anyone suggest a solution? Thanks in advance to.

I made some corrections to you code:

Option Explicit

Private Sub Workbook_Open()

    Dim Rng As Range
    Dim cel As Range

    Sheet1.ComboBox1.Clear
    Sheet1.ComboBox2.Clear

    Set Rng = Sheet2.Range("A3", Sheet2.Cells(Rows.Count, "A").End(xlUp))

    With CreateObject("Scripting.Dictionary")

        For Each cel In Rng
            If Not .exists(cel.Value) Then
                .Add cel.Value, Nothing
            End If
        Next cel

        Sheet1.ComboBox1.List = .keys

    End With

End Sub

If I manually add an item to ComboBox and save the workbook, close the workbook, then re-open the workbook then the list reverts to a distinct list from Sheet2 .

Can you try it?

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM