Home » excel » excel – Handle visible cells in vba

excel – Handle visible cells in vba

Posted by: admin April 23, 2020 Leave a comment


I have a Worksheet named ‘Abschluss’. In this worksheet I use filter to get the data-range I want to handle with my vba script. So i only want to handle the visible rows.
My vba Script looks like

For Each i In Worksheets("Abschluss").SpecialCells(xlCellTypeVisible).Rows
    If (WorksheetFunction.CountIf(Range("B2:B" & i), Cells(i, 2)) = 1) Then _
        Umsetzung_Kapitel_1.AddItem Cells(i, 2)

This doesn’t work, I get runtime-error 438. Do you know where the problem is?
I assume that Worksheets("Abschluss").SpecialCells(xlCellTypeVisible).Rows returns the wrong data-type, but I couldn’t fix it.

How to&Answers:

It looks like you are trying to populate a combobox or a listbox with unique items, possibly in a UserForm?

Try this

Private Sub UserForm_Initialize()
    Dim cUnique As Collection
    Dim Rng As Range
    Dim Cell As Range
    Dim sh As Worksheet
    Dim vNum As Variant

    Set sh = ThisWorkbook.Sheets("Abschluss")
    Rws = sh.Cells(Rows.Count, "B").End(xlUp).Row
    Set Rng = sh.Range(sh.Cells(2, 2), sh.Cells(Rws, 2)).SpecialCells(xlCellTypeVisible)

    Set cUnique = New Collection

    On Error Resume Next
    For Each Cell In Rng.Cells
        cUnique.Add Cell.Value, CStr(Cell.Value)
    Next Cell
    On Error GoTo 0

    For Each vNum In cUnique
        ComboBox1.AddItem vNum
    Next vNum

End Sub


Change to

Dim i As Long
Dim colCount As Long: colCount = Worksheets("Abschluss").SpecialCells(xlCellTypeVisible).Rows.Count
For i = 1 to colCount