如何在列表框VBA中显示/删除4个单元格的行项目

时间:2018-03-19 07:53:12

标签: excel vba excel-vba

我有一个列表框,需要显示一行中的项目。这里每个项目相隔4个单元格。所以我试图显示它,但它显示项目和银行单元格。我试图抵消,但没有用。

enter image description here

所以在这里,列表框应该显示这些项目A,B,C没有空格也应该正确删除。

我的代码:

Sub UserForm_Initialize()
Range("B1").Select
End Sub
Private Sub CommandButton1_Click()
If TextBox1.Value = "" Then
    MsgBox ("Please Add something")

Else
    ActiveCell = TextBox1.Value
    ActiveCell.Offset(1, 0).Select
    ActiveCell.Value = "a"
    ActiveCell.Offset(0, 1).Select
    ActiveCell.Value = "b"
    ActiveCell.Offset(0, 1).Select
    ActiveCell.Value = "c"
    ActiveCell.Offset(0, 1).Select
    ActiveCell.Value = "d"

    ActiveCell.Offset(-1, 1).Select

    End If

'For i = 3 To ActiveSheet.Cells(Rows.Count, 3).End(xlUp).Row Step 2       

'Next i
  'ListBox1.RowSource = "Sheet3!1:1" & Range("A" & Column.Count).End(xlUp).Column


  Dim lCol As Long

'Determine last column
lCol = Cells(1, Columns.Count).End(xlToLeft).Column
Dim rngSource As Range
'Set range source data to be included in listbox
Set rngSource = Worksheets("Sheet3").Range(Cells(1, 2), Cells(1, lCol))

'Populate listbox with range source data
'ListBox1.List = rngSource.Cells.Value
Call resetForm

End Sub

enter image description here

1 个答案:

答案 0 :(得分:1)

尝试以下方法。您可能希望在添加之前清除。这假设一个表单控件列表框。

Option Explicit

Sub test()

Dim myListBox As Object
Set myListBox = ActiveSheet.Shapes("List Box 1").OLEFormat.Object

myListBox.AddItem Range("B1")
myListBox.AddItem Range("F1")
myListBox.AddItem Range("J1")

End Sub

或者找到行中的最后一列,创建一个从B1到此列的范围并循环添加项目:

With ActiveSheet

    Dim loopRange As Range

    Set loopRange = .Range(.Cells(1, 2), .Cells(1, .Cells(1, .Columns.Count).End(xlToLeft).Column)).SpecialCells(xlCellTypeConstants)

End With

Dim currentCell As Range

For Each currentCell In loopRange

    myListBox.AddItem currentCell

Next currentCell

Data should be coming in this listbox