设置UsedRange的起点

时间:2015-11-03 21:34:30

标签: excel vba excel-vba combobox

我有一个组合框下拉列表,用于填充列表中的项目,其功能是按照以下代码收集的组合框中的字符类型过滤到下拉选项

Option Explicit

Private cLstPrior As Variant

Private Sub Worksheet_SelectionChangePrior(ByVal Target As Range)
    cLstPrior = Application.Transpose(Database.Columns("1:1").SpecialCells(xlCellTypeConstants, 23)) 'set module-level variable
    Tool.priorCmb.List = cLstPrior        'initialize ComboBox to range Col A (UsedRange only)
    Tool.priorCmb.ListIndex = -1     'set ComboBox value to empty
End Sub

Private Sub priorCmb_Change()
   filterComboListPrior Tool.priorCmb, cLstPrior
End Sub

Private Sub priorCmb_KeyPress(ByVal KeyAscii As MSForms.ReturnInteger)
    Tool.priorCmb.DropDown
End Sub

Private Sub priorCmb_GotFocus()   'or _MouseDown()
    Tool.priorCmb.DropDown
End Sub

Public Sub filterComboListPrior(ByRef cmbPrior As ComboBox, ByRef dLstPrior As Variant)
    Dim itmPrior As Variant, lstPrior As String, selPrior As String


    Application.EnableEvents = False
    With cmbPrior
        selPrior = .Value
        If IsEmpty(cLstPrior) Then cLstPrior = Worksheets("Database").Columns("1:1").SpecialCells(xlCellTypeConstants, 23)
        For Each itmPrior In cLstPrior
            If Len(itmPrior) > 1 Then If InStr(1, itmPrior, selPrior, 1) Then lstPrior = lstPrior & itmPrior & "||"
        Next
        If Len(lstPrior) > 1 Then .List = Split(Left(lstPrior, Len(lstPrior) - 2), "||") Else .List = dLstPrior
    End With
    Application.EnableEvents = True

End Sub

组合框需要填充的数据全部来自第1列,在这种情况下是任何包含字符的单元格。 问题是A1和A2处有空白单元格,因此空白条目会在以后填充组合框下拉列表。我试图强制范围只包括具有值的单元格,但我在If IsEmpty(cLstPrior) Then cLstPrior = Worksheets("Database").Columns("1:1").SpecialCells(xlCellTypeConstants, 23)得到应用程序定义或对象定义的错误 我似乎无法弄清楚这一点。另外,我的Application.Transpose行为是否正确?

3 个答案:

答案 0 :(得分:0)

而不是:

Database.UsedRange.Rows(2)

尝试:

Database.Range(Database.Cells(2,2),Database.Cells(Database.UsedRange.Rows.Count, 2))

答案 1 :(得分:0)

最好使用特殊单元,并遍历具有值的单元格。

Private Sub Worksheet_SelectionChange(ByVal Target As Range)
    Dim rRng As Range, c As Range, ws As Worksheet
    Set ws = Sheets("Database")

    Me.ComboBox1.Clear

    Set rRng = ws.Rows("2:2").SpecialCells(xlCellTypeConstants, 23)
    For Each c In rRng.Cells
        Me.ComboBox1.AddItem c
    Next c

End Sub

答案 2 :(得分:0)

使用“相交”排除列

With Worksheets("Database")
    Set rng = Application.Intersect(.UsedRange.Rows(2), .Cells.Resize(.Columns.Count - 1).Offset(1))
    End With

将有问题的行更改为新定义的范围

If IsEmpty(cLst) Then cLst = rng