如何使用VBA在Excel中循环遍历所有列

4

基于我创建的教程,我在Excel中创建了一个小型联系人管理器,并对其进行了一些调整以适应我的需要。到目前为止,作为一个VBA新手,这对我来说是一个不错的小经验 :)

一些背景信息

我有两个工作表。第一个包含人员及其地址。第二个包含所有他们的联系方式(以避免在第一个工作表上具有无限的列来区分电话、电子邮件等)。这些详细信息是根据第一个工作表中数据的ID匹配并呈现在两个列表框中。 搜索值存储在C5中。C4引用特定类型数据的列(如名称、地址、地点),当我想搜索所有列时,该列为空。

问题

当我尝试搜索某些内容时,它只返回找到的第一项并停止。我猜我需要创建一个循环来获取所有项目,但迄今为止我还没有成功创建一个正常运行的循环。

到目前为止我拥有的代码

Private Sub btnZoeken_Click()
'dim the variables
Dim Crit As Range
Dim FindMe As Range
Dim DataSH As Worksheet

On Error GoTo errHandler:

Set DataSH = Sheet1

Application.ScreenUpdating = False

'Default search criteria is Alles (all columns).
If Me.cboHeader.Value <> "Alles" Then
        If Me.txtZoeken = "" Then
        DataSH.Range("C5") = ""
        Else
        DataSH.Range("C5") = "*" & Me.txtZoeken.Value & "*"
        End If
End If

'if all columns is selected
If Me.cboHeader.Value = "Alles" Then
'find the value in the column
    Set FindMe = DataSH.Range("B9:H30000").Find(What:=txtZoeken, LookIn:=xlValues, _
    LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
    MatchCase:=False, SearchFormat:=False)
'variable for criteria header
    Set Crit = DataSH.Cells(8, FindMe.Column)
'if no criteria is added to the search
        If Me.txtZoeken = "" Then
        DataSH.Range("C5") = ""
        DataSH.Range("C4") = ""
        Else
        'add values from the search
        DataSH.Range("C4") = Crit
            If Crit = "ID" Then
            DataSH.Range("C5") = Me.txtZoeken.Value
            Else
            DataSH.Range("C5") = "*" & Me.txtZoeken.Value & "*"
            End If
        End If
End If


'filter the data
DataSH.Range("B8").CurrentRegion.AdvancedFilter Action:=xlFilterCopy, _
CriteriaRange:=Range("Data!$C$4:$C$5"), CopyToRange:=Range("Data!$N$8:$T$8"), _
Unique:=False
'add the dynamic data to the listbox
lstResult.RowSource = DataSH.Range("outdata").Address(external:=True)

'show which column contained to selected value (for now only for debugging)
Me.RegTreffer.Value = DataSH.Range("C4")

'error handler
On Error GoTo 0
Exit Sub
errHandler:
'if error occurs then show me exactly where the error occurs
MsgBox "No result for " & txtZoeken.Text & " in " & Me.cboHeader.Value
'clear the listbox if no match is found
Me.lstResult.RowSource = ""
Exit Sub
End Sub

我应该如何构建循环来获取所有列中具有匹配值的行?是否需要创建两个不同的循环?一个用于在所有列中搜索,另一个用于搜索特定列,或者无论哪种方式都可以?

1个回答

3

首先,直接回答你的问题:

Private Sub LookForMatches()

    ' Set a reference to our range
    Dim MyRange As Range
    Set MyRange = ThisWorkbook.Sheets("Sheet1").Range("A1:C4")
    
    ' Loop through all of the cells in the range
    Dim Cell As Variant
    For Each Cell In MyRange.Cells
    
        ' In this example, we will check if the cell equals 1
        ' If it does, display a message informing the user of the match and the location of the cell
        If Cell.Value = 1 Then
            MsgBox "Match found.  The cell " & Cell.Address & " equals 1."
        End If
    
    Next Cell
    
End Sub

这是我例子中使用的Sheet1上的数据。

用于示例的数据范围

希望这个模板足够说明如何循环遍历范围并查找信息。如果你只关心单元格所在行而不是完整地址,可以使用Cell.Row方法代替Cell.Address方法。

其次,通常不应该像这样循环遍历数据。这比其他方法要慢得多。例如,我们可以将此范围存储在一个数组中,然后使用数组而不是范围进行操作。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接