我有一个excel文件,其中包含备件的序列号(sn)和生产日期(pd)以及许多其他额外数据。
到目前为止,为了找到一些引用特定sn的额外数据,我在excel中使用了搜索功能。然而,一个sn可以有几个pd,因此我有时会点击搜索按钮超过一百次....
pd始终位于列所在列左侧的列中。但是有超过200列,它们的位置不固定...即。有时pd位于第22列,sn位于第23列,但有时pd位于第66列,sn位于第67列。始终位于左侧带有pd的相邻单元格中。
So far I have the following code:
Sub FindBoard()
Dim LastRow As Long
Dim LastColumn As Long
Dim LastCell As Range, NextCell As Range
Dim r As Long
Dim m As Long
Dim sthlh As Long
With Worksheets("Sheet3")
' Find LastRow. Works Best. 1st and last cells can be empty
If WorksheetFunction.CountA(Cells) > 0 Then
'Search for any entry, by searching backwards by Rows.
LastRow = Cells.Find(What:="*", After:=[A1], _
SearchOrder:=xlByRows, _
SearchDirection:=xlPrevious).Row
'Search for any entry, by searching backwards by Columns.
LastColumn = Cells.Find(What:="*", After:=[A1], _
SearchOrder:=xlByColumns, _
SearchDirection:=xlPrevious).Column
'MsgBox "Last Cell" & vbCrLf & vbCrLf & Cells(LastRow, LastColumn).Address
MsgBox "The Last Row is: " & vbCrLf & vbCrLf & LastRow
MsgBox "The Last Column is: " & vbCrLf & vbCrLf & LastColumn
End If
' Number of columns based on actual size of log range NOT MyAr(n)
Set NextCell = Worksheets("Sheet3").Cells(LastRow + 1, (LastColumn - 10))
End With
For r = 1 To LastRow
'For sthlh = 2 To LastColumn**
If Cells(r, "AP") = "0600263" Then
If Cells(r, "AO") = "4112" Then
Exit For
End If
End If
'Next sthlh**
Next r
If r > LastRow Then
MsgBox " not found"
Else
' found in row
MsgBox "The board u r looking for is in row: " & vbCrLf & vbCrLf & r
Rows(r).Select
End If
End Sub
我尝试使用double asterix **添加两行,以便不像我在代码中那样使用特定列,但是要像这样:
.....
For r = 1 To LastRow
For sthlh = 2 To LastColumn
If Cells(r, sthlh ) = "0600263" Then
If Cells(r, sthlh-1) = "4112" Then
Exit For
End If
End If
Next sthlh
Next r
.....
其中4112是pd 和0600263是sn
我的目标是迭代遍历Excel工作表的每个PAIR OF COLUMNS,当我找到sn来检查pd是否是所需的。如果是,则选择该行,以便我可以看到我想要的额外数据。
知道我做错了吗??? 在此先感谢!!!
答案 0 :(得分:0)
试试这个:
Option Explicit
Sub FindBoard()
Dim LastRow As Long, LastColumn As Long
Dim r As Long
Dim sthlh As Long
Dim found As Boolean
Dim Paire As Range
LastRow = Sheets("Sheet3").Range("A" & Rows.Count).End(xlUp).Row
LastColumn = Sheets("Sheet3").Cells(1, Columns.Count).End(xlToLeft).Column
found = False
r = 0
Do Until r > LastRow Or found = True
r = r + 1
For sthlh = 2 To LastColumn
If Cells(r, sthlh) = "0600263" Then
If Cells(r, sthlh - 1) = "4112" Then
found = True
Set Paire = Range(Cells(r, sthlh - 1), Cells(r, sthlh))
Exit For
End If
End If
Next sthlh
Loop
If found = False Then
MsgBox " not found"
Else
' found in row
MsgBox "The board u r looking for is in row: " & vbCrLf & vbCrLf & Paire.Address
Paire.Select
End If
End Sub