如果单元格值包含特定字符串,则添加到列表框

时间:2020-10-08 16:09:45

标签: excel vba listbox range

我正在尝试根据搜索范围C列中单元格的值,将数据添加到用户窗体上的列表框。如果C列中的单元格包含某个字符串,我希望将其添加到列表框中。

以下代码是我所掌握的,但是它返回的是一个没有错误的空列表框。

Private Sub OptionButton12_Click()

Dim I As Integer
Dim lastRow As Integer
Dim searchString As String

searchString = "LISTBOXENTRY"

With ThisWorkbook.Sheets("Sheet1")
lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
End With

Plybooks.ListBox1.Clear
For I = 1 To lastRow
    If Cells(I, 3).Value = searchString Then
        Plybooks.ListBox1.AddItem Range("A" & I)
    End If
Next I

End Sub

2 个答案:

答案 0 :(得分:0)

尝试使用下面的脚本,请告诉我它是否有效!

根据上面的脚本,我假设了一些数据框尺寸。请让我知道是否正确,以便进行调整。

我假设您正在处理第一张工作表(sheets(1)),而col C是用于针对“ searchString”变量进行值检查的列。 (如果为true,则将值附加到listbox1中)

谢谢

Private Sub OptionButton12_Click()

Dim lastRow As Integer
Dim searchString As String
Dim wb As Workbook
Dim sRng As Range
Dim cel As Range

'assign current wb into wb workbook object
Set wb = ThisWorkbook

'assign str you want to search into variable
searchString = "LISTBOXENTRY"

'find last row number in colC (3) using crow function. (assuming you want to do a check on every cell listed in column C)
lastRow = crow(1, 3)

plybooks.listbox1.Clear

'assign range object using dataframe dimensions based on row 1 col C (lbound), to lastrow col3 (ubound)
With wb.Sheets(1)

    Set sRng = .Range(.Cells(1, 3), .Cells(trow, 3))
    
End With

'loops through each cel
For Each cel In sRng

    If cel.Value = searchString Then
        
        'adds item  into listbox1 if conditional statement is True
        plybooks.listbox1.AddItem Item:=cel.Value
    
    Else
    End If

Next cel

End Sub


Private Function crow(s As Variant, c As Integer)

    crow = Sheets(s).Cells(Rows.Count, c).End(xlUp).Row

End Function

答案 1 :(得分:0)

如果单元格包含某个值,则使用以下方法在多个工作表的范围内添加单元格值:

Public Sub PlybookListbox()

'Clear fields before start
Plybooks.ListBox1.MultiSelect = 0
Plybooks.ListBox1.Clear
Plybooks.ListBox1.Value = ""
Plybooks.ListBox1.MultiSelect = 2

Dim AllAreas(2) As Range, Idx As Integer, MyCell As Range, TargetRange As Range
Dim lastrowFrontWing As Long
Dim lastrowNose As Long
Dim lastrowBargeboard As Long

lastrowFrontWing = Worksheets("Front Wing").Cells(Rows.Count, 2).End(xlUp).Row
lastrowNose = Worksheets("Nose").Cells(Rows.Count, 2).End(xlUp).Row
lastrowBargeboard = Worksheets("Bargeboard & SPV").Cells(Rows.Count, 2).End(xlUp).Row

    Set AllAreas(0) = Worksheets("Front Wing").Range("c6:c" & lastrowFrontWing)
    Set AllAreas(1) = Worksheets("Nose").Range("c6:c" & lastrowNose)
    Set AllAreas(2) = Worksheets("Bargeboard & SPV").Range("c6:c" & lastrowBargeboard)

Plybooks.ListBox1.Clear

For Idx = 0 To 2
    For Each MyCell In AllAreas(Idx).Cells
        If InStr(1, MyCell.Value, "(FS)") > 0 Then
            Plybooks.ListBox1.AddItem MyCell.Value
        End If
    Next MyCell
Next Idx

End Sub