提问人:Jarod Zillinger 提问时间:11/9/2023 最后编辑:DomenicJarod Zillinger 更新时间:11/10/2023 访问量:54
在excel VBA中使用用户窗体中的列表框查找行和列的交集?
Finding intersection of a row and column using listboxes in a userform in excel VBA?
问:
我在同一个工作簿中有多个格式相同的 excel 工作表。在每个工作表中,我都有 a2:a416 的日期,我在 b1、d1、f1、h1、j1、l1、n1、p1、r1、t1、v1 和 x1 处有数字作为标题。在用户窗体中,我有两个列表框,一个包含标题为 ListBoxRows 的日期,另一个包含标题为 ListBoxColumns 的数字。我正在尝试编写VBA代码,在我按下按钮后,它从ListBoxRows ListBox中获取值并选择匹配的行,然后从ListBoxHeaders中获取值并选择匹配的列,然后选择该行和列相交的单元格。例如,如果日期 11/29/23 位于单元格 a18 中,而数字 0.00814 是 D 列的标题,则我需要它来最终选择单元格 d18。
Sub FindColumn()
Dim selectedValue As String
Dim headerRange As Range
Dim headerCell As Range
Dim targetColumn As Long
' Get the selected value from the list box
selectedValue = ListBoxHeaders.Value
' Set the range of headers (assuming headers are in the first row)
Set headerRange = activeSheet.Rows(1)
' Loop through each cell in the header range
For Each headerCell In headerRange
' Check if the header matches the selected value
If headerCell.Value = selectedValue Then 'error on this line
' Get the column number of the matching header
targetColumn = headerCell.Column
' Exit the loop since we found the match
Exit For
End If
Next headerCell
' Display the column number
MsgBox "The column number for " & selectedValue & " is: " & targetColumn
End Sub
我想从选择柱子开始让我的脚湿透,但它不起作用。它在粗体行处给出类型不匹配的错误代码。任何帮助将不胜感激。
答:
0赞
Tim Williams
11/10/2023
#1
当您想要完全匹配时,使用更简单:Application.Match
Sub FindColumn()
Dim selectedValue As String, m As Variant
selectedValue = ListBoxHeaders.Value
Debug.Print "Selected:", selectedValue
m = Application.Match(selectedValue, ActiveSheet.Rows(1), 0)
If Not IsError(m) Then 'got a match (`m` will be an error if not match)
MsgBox "The column number for '" & selectedValue & "' is: " & targetColumn
Else
MsgBox "No match for '" & selectedValue & "'"
End If
End Sub
评论
For Each headerCell In headerRange.Cells
ListBoxHeaders