Excel 在遍历列时匹配单元格对,然后返回新的单元格对
我正在尝试编写一个代码,它将获取一个单元格,然后遍历另一列以查找匹配项,一旦找到匹配项,它将匹配同一行中的其他两个单元格,并返回第5个和第6个单元格的值。但是,它不起作用!有什么建议吗Excel 在遍历列时匹配单元格对,然后返回新的单元格对,excel,vba,excel-formula,pattern-matching,Excel,Vba,Excel Formula,Pattern Matching,我正在尝试编写一个代码,它将获取一个单元格,然后遍历另一列以查找匹配项,一旦找到匹配项,它将匹配同一行中的其他两个单元格,并返回第5个和第6个单元格的值。但是,它不起作用!有什么建议吗 Sub rates() Dim i As Integer For i = 2 To 2187 If Cells(i, 1).Value = Cells(i, 11).Value Then If Cells(i, 2).Value = Cells(i, 12).Valu
Sub rates()
Dim i As Integer
For i = 2 To 2187
If Cells(i, 1).Value = Cells(i, 11).Value Then
If Cells(i, 2).Value = Cells(i, 12).Value Then
Cells(i, 20) = Cells(i, 1).Value
Cells(i, 21) = Cells(i, 11).Value
Cells(i, 22) = Cells(i, 4).Value
Cells(i, 23) = Cells(i, 16).Value
Else
Cells(i, 24) = "No match"
End If
End If
Next i
End Sub
尝试完全限定单元格对象,即
sheet1.单元格(i,1).值
等,或用语句封装在中,即
with sheet1
if .cells(i,X) = .cells(i,Y) then
'...etc
end with
我认为一个范围的默认属性是“Value”,但试着把.Value也放在所有单元格的末尾。。。就像你为他们中的一半所做的:)
[编辑/添加:]
。。。如果不能做到这一点,您实际上在任何时候都不会搜索整个列:请尝试以下操作:
Sub rates()
Dim i As Integer
Dim rgSearch As Range
Dim rgMatch As Range
Dim stAddress As String
Dim blMatch As Boolean
With wsSheet
Set rgSearch = .Range(.Cells(x1, y1), .Cells(x2, y2)) ' Replace where appropriate (y = 1 or 11 i guess, x = start and end row)
End With
For i = 2 To 2187
Set rgMatch = rgSearch.Find(wsSheet.Cells(i, y)) ' y = 1 or 11 (opposite of above!)
blMatch = False
If Not rgMatch Is Nothing Then
stAddress = rgMatch.Address
Do Until rgMatch Is Nothing Or rgMatch.Address = stAddress
If rgMatch.Offset(0, y).Value = Cells(i, 12).Value Then
Cells(i, 20) = Cells(i, 1).Value
Cells(i, 21) = Cells(i, 11).Value
Cells(i, 22) = Cells(i, 4).Value
Cells(i, 23) = Cells(i, 16).Value
blMatch = True
Else
End If
Set rgMatch = rgSearch.FindNext(rgMatch)
Loop
End If
If Not blMatch Then
Cells(i, 24) = "No match"
End If
Next i
End Sub
我在这里做了很多假设,还有一些变量需要替换。您也可以使用application.worksheetfunction.match,但是.find更快、更棒谢谢您的宝贵意见!这段代码是否执行了我要求它执行的操作?我需要一对单元格与另一对单元格在两个不同的列中进行比较,我不想将一对单元格与另一列中的另一对单元格进行比较我想将一对单元格与另一列中的每个单元格进行比较,然后返回匹配项。好吧,我想这只是我最初的观察结果。。。希望它能神奇地解决所有问题,而不需要我多想:)你的代码与你的问题不匹配:你说你正在逐行检查,试图在列中找到匹配项,但你的代码只在同一行中查找匹配项。。。(也就是说,“我”在任何情况下都是一样的)我会用一个提示更新我的答案哇,这看起来既令人印象深刻又吓人!LOL,我尝试应用这个代码,它运行一个运行时错误“424”,并说在我的插入(1,1)和(2187,1)的Rang.WStl需要在有效的…将其设置为工作表,或者直接使用实际的工作表对象。。。i、 e.默认情况下,excel创建工作表“工作表1”“工作表2”等。。。i、 e.选项卡中的文本名称显示“表1”等。。。但它们也可以作为对象直接访问,方便地命名为sheet1、sheet2、sheet3等(即没有空间),因此这两个东西都是有效的:thisworkbook.sheets(“Sheet 1”)。activate和sheet1.activate。。。您可以在VBA中的“属性”中重命名该代码名。。。将其更改为wsSheet,例如。。。或设置wsSheet=thiswoolk.sheets(“工作表1”)