VBA - for For循环中的每个“循环”仅在第一次起作用

时间:2015-06-15 11:19:47

标签: vba for-loop repeat

我正在尝试在for-loop中使用一个范围内的“for each”-loop。它在第一次工作时很好(对于sheet1)但是在第二圈中代码在测试1和2之间停止(错误400),这必须意味着在“每个循环”中。有谁知道为什么?

我的声明(Dim目录为字符串,fileName为字符串,工作表为工作表,i为整数,j为整数     Dim x As Range,y As Range,urfFile As String,sheetNbr As Integer)

For sheetNbr = 1 To Workbooks(fileName).Worksheets.Count
        j = NoDataActive() 'see which row typing should start on 

    Set x = Workbooks(fileName).Worksheets(sheetNbr).Range("a2") 'start active search at A2
    Set y = Workbooks(fileName).Worksheets(sheetNbr).Range("a2") 'start possible search at A2
    Workbooks("Utkast1.xlsm").Worksheets("Active").Cells(sheetNbr, 5).Value = 1 'test

    'For the active product numbers in the sheet
    For Each x In Workbooks(fileName).Worksheets(sheetNbr).Range(Cells(1, 1), Cells(Range("A" & Rows.Count).End(xlUp).Row, 1))

        Workbooks("Utkast1.xlsm").Worksheets("Active").Cells(sheetNbr, 6).Value = 2 'test

        If x.Offset(0, 2).Value() = "J" Then
            Workbooks("Utkast1.xlsm").Worksheets("Active").Cells(j, 1).Value = Workbooks(fileName).Worksheets(sheetNbr).name 'print store number
            Workbooks("Utkast1.xlsm").Worksheets("Active").Cells(j, 2).Value = x.Value() 'print BNR
            Workbooks("Utkast1.xlsm").Worksheets("Active").Cells(j, 3).Value = "URF" 'print data source
            j = j + 1
        End If
    Next x
Next sheetNbr

1 个答案:

答案 0 :(得分:0)

为什么不使用2个For Each循环?

请注意变量的名称,Sheet已经是VBA语言的元素,因此我将其重命名为aSheet

当您使用此Workbooks("Utkast1.xlsm").Worksheets("Active")时,您的意思是采用ActiveSheet还是您有一张名为Active的工作表?

For Each aSheet In Workbooks(Filename).Worksheets
    j = NoDataActive() 'see which row typing should start on
    Set x = Workbooks(Filename).Worksheets(sheetNbr).Range("a2") 'start active search at A2
    Set y = Workbooks(Filename).Worksheets(sheetNbr).Range("a2") 'start possible search at A2

    Set Ws = Workbooks("Utkast1.xlsm").Worksheets("Active")
    Ws.Cells(aSheet.Index, 5).Value = 1 'test
    'For the active product numbers in the sheet
    For Each x In aSheet.Range(aSheet.Cells(1, 1), aSheet.Cells(aSheet.Range("A" & aSheet.Rows.Count).End(xlUp).Row, 1))
        Ws.Cells(sheetNbr, 6).Value = 2 'test
        If x.Offset(0, 2).Value() = "J" Then
            Ws.Cells(j, 1).Value = aSheet.Name 'print store number
            Ws.Cells(j, 2).Value = x.Value() 'print BNR
            Ws.Cells(j, 3).Value = "URF" 'print data source
            j = j + 1
        End If
    Next x
Next aSheet

Set x = Nothing
Set y = Nothing
Set Ws = Nothing