【问题标题】:VBA For Each Loop not working with the Next iVBA For Each Loop 不适用于 Next i
【发布时间】:2015-11-02 12:22:14
【问题描述】:
Sub ISIN()
    Dim RNG As Range
    Set RNG = Range("C20").End(xlDown).Select
    Dim i As Variant
    Dim y As Variant    
    Dim t As Range    
    Set t = Range("T:T")    

    For Each i In Range("C20,C500")
        For Each y In Range("DATAS!A6,DATAS!A100")   
            If Cells(i, 1) = Cells(y, 1) Then
                t = "All Good Here"
            Else: Range("RNG") = Cells(y, 1)
            End If
        Next y
    Next i

End Sub

【问题讨论】:

  • 像这样使用的 i 和 y 将需要是 i.row 和 y.row.... 引用中的 RNG 正在寻找一个名为 RNG 的命名范围,它没有查看名为 RNG 的范围变量, 使用 RNG.value = cells(y.row,1)
  • 你还需要在Next y之前移动End If
  • 那么你到底想做什么?

标签: vba for-loop each


【解决方案1】:

如果我猜对了,这就是你要找的东西:

Sub ISIN()

    Dim RNG As Range
    Dim Rg1 As Range
    Dim Rg2 As Range
    Dim t As Range
    Dim Ws As Worksheet
    Dim WsData As Worksheet

    Set Ws = ActiveWorkbook.Sheets("Sheet1")
    Set WsData = ActiveWorkbook.Sheets("DATAS")

    Set RNG = Ws.Range(Ws.Range("C20"), Ws.Range("C" & Ws.Rows.Count).End(xlUp))
    Set t = Ws.Range("T:T")

    For Each Rg1 In RNG
        For Each Rg2 In WsData.Range("A6:A100")
            If Cells(Rg1.Row, 1) = Cells(Rg2.Row, 1) Then
                Application.Intersect(t, Rg1.Row).Value = "All Good Here"
            Else
                Ws.Cells(Rg1.Row, 1) = WsData.Cells(Rg2.Row, 1)
            End If
        Next y
    Next i

    Set Ws = Nothing
    Set WsData = Nothing

    Set RNG = Nothing
    Set t = Nothing

End Sub

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-11-23
    • 2021-05-12
    • 2018-05-07
    • 2017-03-20
    • 1970-01-01
    • 1970-01-01
    • 2018-09-08
    • 1970-01-01
    相关资源
    最近更新 更多