我有以下查找表(名为“格式”): https://ethercalc.org/zs2n0j4u9xdi
我要遍历另一张工作表中的一列,在这里我得到的值与上面“项目”列中的值相同。我想在上面的表中查找这些昵称,并获取它们左侧的两个值,并将它们存储在两个变量中:
这是我的代码,可以获取以下“项目”:
i = 7
currRow = 9
While ThisWorkbook.Sheets("Weights").Cells(i, 3) <> ""
Item = ThisWorkbook.Sheets("Weights").Cells(i, 3).Value
parent = someLookupMethod("Formatting", Item)
child = someLookupMethod("Formatting", Item)
currRow = currRow + 1
i = i + 1
Wend
我将如何实施?
答案 0 :(得分:1)
这里是演示使用“查找”获取数据的行匹配的一种方法。 我在这里将搜索触发器放入命令按钮中(我并没有为按钮命名)。
注意:下面的代码很快完成,对单元格坐标进行硬编码不是使用地址的最佳方法,因为它不灵活。如果您不知道数据的大小,则可以找到最后一列和最后一行,并使用这些数字定义数据范围。
注2:为了放弃工作表变量的创建和命名,我只是在“属性”窗口中给了工作表代码名称,以这种方式进行编码非常快。
代码:
Option Explicit
Private Sub CommandButton1_Click()
Dim Fname As String
Dim MatchRow As Double
Dim MatchRange As Range
'wsSearch named worksheet, you no longer have to care about the WS tab name
'wsData is a named worksheet, you no longer have to care about the WS tab name
'Do this using the properties explorer in design mode (under developer)
'Or create and set your worksheets ... sometimes you have to
Fname = CStr(wsSearch.Cells(2, 3)) 'convert that cell to a string (row, column)
'This simply clears the cells so old search data is not present
wsSearch.Range("C3:C6").Clear
If wsSearch.Cells(2, 3) <> "" Then 'Test there is a name to search
Set MatchRange = wsData.Range("A1:D10").Find(Fname)
If (Not MatchRange Is Nothing) Then
'We have a match
MatchRow = MatchRange.Row 'assign MatchRow and now you can use it in .Cells or .Range definitions
wsSearch.Cells(3, 3) = MatchRow 'Report MatchRow
wsSearch.Cells(4, 3) = wsData.Cells(MatchRow, 2) 'Report Last name
wsSearch.Cells(5, 3) = wsData.Cells(MatchRow, 3) 'Report Address
wsSearch.Cells(6, 3) = wsData.Cells(MatchRow, 4) 'Report Phone
'left justify everything, by default numbers are right justified
wsSearch.Range("C3:C6").HorizontalAlignment = xlLeft
Else
wsSearch.Cells(3, 3) = "NA"
wsSearch.Cells(4, 3) = "NA"
wsSearch.Cells(5, 3) = "NA"
wsSearch.Cells(6, 3) = "NA"
MsgBox "The name " & Fname & " was not found"
End If
Else
MsgBox "No Name to Search, try again"
End If
End Sub
这是工作表的样子:
您将发现更大的挑战是定义什么是数据范围及其布局,以及在构建应用程序时将数据及其布局放置在何处。
快乐编码!
如果这对您有帮助,请接受答案-WWC