我正在尝试编写一个宏,提示用户输入值并执行以下操作:
- Search for the value in column B and select the first cell where the value is found
- Return the correspondong value in column L and M of the selected cell's row within a message box
- Then once the user hits "ok", the macro will find and select the next cell in column B with the search criteria, and repeat the above steps
- Once all of the cells with the search criteria in column B have been searched and found, a message box will communicate that all matches have been found and close loop
下面是我开始使用的代码,并且作为VB的初学者,我无法弄清楚为什么我的循环无法正常工作......请帮忙!
Sub Macro1()
Dim response As String, FndRow As Long, NoMatch As Boolean, LastRow As Long
response = InputBox("Please enter the Column Name to find matching Source File Field Name.")
If response = "" Then Exit Sub
On Error Resume Next
Range("B5").Select
NoMatch = False
LastRow = 0
Do Until NoMatch = True
FndRow = Cells.Find(What:=response, After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False).Row
If FndRow = 0 Then
MsgBox response & " could not be found."
NoMatch = True
ElseIf FndRow < LastRow Then
MsgBox "All " & response & " matches have been found."
NoMatch = True
Else
Range("B" & FndRow).Select
MsgBox "Source File Name: " & Range("L" & FndRow).Value & vbNewLine & "File Column Name: " & Range("M" & FndRow).Value
LastRow = FndRow
End If
Loop
End Sub
答案 0 :(得分:0)
你的查找行为奇怪,因为你正在寻找'水平'匹配。您需要使用SearchOrder:= xlByColumns
FndRow = Cells.Find(What:=response, After:=ActiveCell, LookIn:=xlFormulas, _
LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext, _
MatchCase:=False, SearchFormat:=False).Row
答案 1 :(得分:0)
我会使用过滤器而不是查找循环:
Sub tgr()
Dim rngVis As Range
Dim VisCell As Range
Dim sFind As String
sFind = InputBox("Please enter the Column Name to find matching Source File Field Name.")
If Len(Trim(sFind)) = 0 Then Exit Sub 'Pressed cancel
Application.ScreenUpdating = False
With Intersect(ActiveSheet.UsedRange, ActiveSheet.Columns("B"))
.AutoFilter 1, sFind
On Error Resume Next
Set rngVis = .Offset(1).Resize(.Rows.Count - 1).SpecialCells(xlCellTypeVisible)
On Error GoTo 0
.AutoFilter
End With
Application.ScreenUpdating = True
If rngVis Is Nothing Then
MsgBox sFind & " could not be found."
Else
For Each VisCell In rngVis.Cells
MsgBox "Source File Name: " & VisCell.Worksheet.Cells(VisCell.Row, "L").Text & vbNewLine & _
"File Column Name: " & VisCell.Worksheet.Cells(VisCell.Row, "M").Text
Next VisCell
End If
End Sub