我需要遍历Column X中Sheet1上的所有行,抓取它的值,然后看看值是否是存储在Sheet 2列A和B上的BETWEEN数字组合。如果value介于两者之间,则显示Sheet 2 Column中的值Sheet 1列Y中的C(将是一个非常简单的SQL查询)。
我在VBA上非常生疏,所以当匹配时我无法退出内部循环,并将Value从Sheet2粘贴到Sheet1。
Sub FindBetweenIP()
Dim ws1 As Worksheet
Set ws1 = Sheets(1)
Dim ws2 As Worksheet
Set ws2 = Sheets(2)
For Each cell In ws1.Range("X2:X" & ws1.Range("X" & Rows.Count).End(xlUp).Row)
For Each cell2 In ws2.Range("A2:A" & ws1.Range("A" & Rows.Count).End(xlUp).Row)
ip_range1 = cell2.Value2
ip_range2 = cell2.Offset(0, 1).Value2
isp = cell2.Offset(0, 2).Value2
If (cell.Value >= ip_range1 And cell.Value <= ip_range2) Then
cell.Offset(0, 1).Value2 = isp 'Seems to be not working
' ALSO, VALUE FOUND-- EXIT INNER LOOP
End If
Next
Next
End Sub
答案 0 :(得分:3)
您正在寻找表达式“退出”。在这种情况下,它看起来像这样:
For i = 1 to 10
[Do statements]
[If Test]
Exit For
[End If]
Next i
以这种方式退出循环基本上就像代码被跳转到“Next i”一样,我已经等于最大循环值。
答案 1 :(得分:3)
除了'Eh'Benon所说的关于Exit For
的等级之外,你对第二个for循环范围有一点脱节:
For Each cell2 In ws2.Range("A2:A" & ws1.Range("A" & Rows.Count).End(xlUp).Row)
你从ws2开始,但你在里面指的是ws1
将其更改为:
For Each cell2 In ws2.Range("A2:A" & ws2.Range("A" & ws2.Rows.Count).End(xlUp).Row)
答案 2 :(得分:0)
在适当尊重我的前辈的情况下,我发现在这种情况下,接近出口并不能正确地同步外圈和内圈。我已经找到了另一种正常工作并给出正确结果的方法。我有待纠正,因为我在VBA的专长可能不是我的老年人和更有经验的人在这里的水平。
Sub FindBetweenIP()
Dim ws1 As Worksheet
Set ws1 = Sheets(1)
Dim ws2 As Worksheet
Set ws2 = Sheets(2)
For Each cell In ws1.Range("X2:X" & ws1.Range("X" & Rows.Count).End(xlUp).Row)
Foundone = False
For Each cell2 In ws2.Range("A2:A" & ws2.Range("A" & Rows.Count).End(xlUp).Row)
If cell2.Row = cell.Row And Foundone = False Then
ip_range1 = cell2.Value2
ip_range2 = cell2.Offset(0, 1).Value2
isp = cell2.Offset(0, 2).Value2
If (cell.Value >= ip_range1 And cell.Value <= ip_range2) Then
cell.Offset(0, 1).Value2 = isp
Foundone = True
End If
End If
Next
Next
End Sub
答案 3 :(得分:-1)
在VBA中你应该使用&#39; goto&#39;命令。 EG:
Sub FindBetweenIP()
Dim ws1 As Worksheet
Set ws1 = Sheets(1)
Dim ws2 As Worksheet
Set ws2 = Sheets(2)
For Each cell In ws1.Range("X2:X" & ws1.Range("X" & Rows.Count).End(xlUp).Row)
For Each cell2 In ws2.Range("A2:A" & ws1.Range("A" & Rows.Count).End(xlUp).Row)
ip_range1 = cell2.Value2
ip_range2 = cell2.Offset(0, 1).Value2
isp = cell2.Offset(0, 2).Value2
If (cell.Value >= ip_range1 And cell.Value <= ip_range2) Then
cell.Offset(0, 1).Value2 = isp
GoTo ExitInnerLoop:
End If
Next
ExitInnerLoop:
Next
End Sub