Excel VBA Findnext问题
此代码一直有效,直到在*********之间输入编码。我试图同时执行两个不同的搜索。有人能解释一下我做错了什么吗?谢谢Excel VBA Findnext问题,excel,vba,Excel,Vba,此代码一直有效,直到在*********之间输入编码。我试图同时执行两个不同的搜索。有人能解释一下我做错了什么吗?谢谢 Public Sub Swap() With Sheet1.Range("A:A") Set LastCell = .Cells(.Cells.Count) End With Set FoundCell = Sheet1.Range("A:A").Find(what:=cusip, after:=LastCell) If Not FoundCell Is Nothin
Public Sub Swap()
With Sheet1.Range("A:A")
Set LastCell = .Cells(.Cells.Count)
End With
Set FoundCell = Sheet1.Range("A:A").Find(what:=cusip, after:=LastCell)
If Not FoundCell Is Nothing Then
FirstAddr = FoundCell.Address
End If
Do Until FoundCell Is Nothing
account = Sheet1.Cells(FoundCell.Row, 2)
''#*************************************
Set FoundCell2 = Sheet2.Range("B:B").Find(what:=account)
If Not FoundCell2 Is Nothing Then
FirstAddr2 = FoundCell2.Address
End If
''#*********************************************
Set FoundCell = Sheet1.Range("A:A").FindNext(after:=FoundCell)
''#Break out of loop when searched through all of the cusips
If FoundCell.Address = FirstAddr Then
Exit Do
End If
Loop
End Sub
你不能同时做两个不同的发现。这是Excel对象模型的一个局限性。只有一个Find“cursor”,当您在A:A中尝试FindNext时,这将是B:B中的某个地方。对于其中一个Find,您必须使用旧的低效循环方式。下面是你如何循环寻找内在的发现
Public Sub Swap()
Dim LastCell As Range
Dim FoundCell As Range
Dim FoundCell2 As Range
Dim FirstAddr As String
Dim FoundAddr As String
Dim Account As Variant
Const CUSIP As String = "Cusip"
Set LastCell = Sheet1.Cells(Sheet1.Rows.Count, 1)
Set FoundCell = Sheet1.Range("A:A").Find(what:=CUSIP, after:=LastCell)
If Not FoundCell Is Nothing Then
FirstAddr = FoundCell.Address
Do
Account = Sheet1.Cells(FoundCell.Row, 2)
FoundAddr = ""
For Each FoundCell2 In Intersect(Sheet2.UsedRange, Sheet2.Columns(2)).Cells
If FoundCell2.Value = Account Then
FoundAddr = FoundCell2.Value
Exit For
End If
Next FoundCell2
If Len(FoundAddr) = 0 Then
FoundAddr = "Not Found"
End If
Debug.Print FoundCell.Address, FoundAddr
Set FoundCell = Sheet1.Range("A:A").FindNext(after:=FoundCell)
Loop Until FoundCell Is Nothing Or FoundCell.Address = FirstAddr
End If
End Sub
你看到的不受欢迎的行为是什么?