[英]How to loop through all columns using VBA in Excel
根據教程,我在 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
我應該如何構建一個循環來獲取任何列中具有匹配值的所有行? 我需要創建兩個不同的循環嗎? 一種用於搜索所有列,另一種用於搜索特定列,或者沒關系?
首先,直接回答您的問題:
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
方法。
其次,您通常不應該像這樣遍歷數據。 它比其他方法慢得多。 例如,我們可以將此范圍存儲在一個數組中,然后使用該數組而不是該范圍。 但這都在您的問題的 scope 之外。 我希望這可以幫到你!
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.