比较来自两张不同纸张的单元格的值
首先我的代码:
Option Explicit Sub UpdateCandidates() Application.ScreenUpdating = False Dim wks As Worksheet, wks2 As Worksheet Dim Lastrow As String, Lastrow2 As String Dim Rng As Range, i As Long, Rng2 As Range, i2 As Long Dim cell As Variant, cell2 As Variant Set wks = ThisWorkbook.Worksheets("Candidates") Lastrow = wks.Range("B" & Rows.Count).End(xlUp).Row If Lastrow > 1 Then cell = wks.Range("B2:B" & Lastrow).Value i = 1: Set Rng = Nothing While i <= Lastrow For i = i To Lastrow Set wks2 = ThisWorkbook.Worksheets("Job live") Lastrow2 = wks2.Range("A" & Rows.Count).End(xlUp).Row If Lastrow2 > 1 Then cell2 = wks2.Range("A2:A" & Lastrow2).Value i2 = 1: Set Rng2 = Nothing While i2 <= Lastrow2 For i2 = i2 To Lastrow2 If cell = cell2(i2, 1) Then MsgBox ("found") End If Next Wend End If Next Wend End If Application.ScreenUpdating = True End Sub
这基本上工作和比较两列,但最后显示一个错误:
“下标超出范围”
我不明白为什么。 我以为这是因为<= Lastrow
但固定到< Lastrow
不改变任何东西。
我也想从第一个表单复制一个值到第二个到一个特定的单元格。 并在我的第二张单元格的单元格下方插入一行。
我也不明白为什么我必须将cell2(i2,1)
与cell2(i2,1)
进行比较,而不是cell2(i2,1)
与cell2(i2,1)
进行比较。 如果我将单元格与单元格2进行比较,则表示types不匹配。 而且如果我在表单中input第二个值,我也有同样的错误。
我的代码有什么问题?
我看到你的代码,这是一个build议
Option Explicit Sub CompareDefinedRanges() Dim rng1, rng2 As Range Dim found As Boolean Dim i, j, foundAt As Integer Set rng1 = Worksheets("Candidates").Range("B2", Worksheets("candidates").Range("B2").End(xlDown).Address) Set rng2 = Worksheets("Job live").Range("A2", Worksheets("Job Live").Range("A2").End(xlDown).Address) 'show items For i = 1 To rng1.Rows.Count found = False foundAt = 0 For j = 1 To rng2.Rows.Count If rng1.Item(i) = rng2.Item(j) Then found = True foundAt = j End If Next j If found Then MsgBox rng1.Item(i).Value & " found at " & CStr(foundAt), , "Candidates" Else MsgBox rng1.Item(i).Value & " not found", , "Candidates" End If Next i Set rng1 = Nothing Set rng2 = Nothing End Sub