Excel VBA循环行不起作用,运行时错误'1004'

时间:2017-11-08 13:55:35

标签: excel vba excel-vba loops for-loop

我正在尝试创建一个循环,该循环通过excel中选定范围内的行,并输出每行的分数,但我得到此错误,指的是for循环中的第一行(设置VARIABLE1)。如果我用“A2”替换.Range(“A”),那么我得到一个输出,但只是第一行自然。如何使代码循环每一行? 代码:

Dim rng As Range
Dim Final_risk_score
Set rng = Worksheets("sheet name").Range("A1:Z100")

For Each Row In rng.Rows
    VARIABLE1 = Worksheets("sheet name").Range("A")
    VARIABLE2 = Worksheets("sheet name").Range("K")
    VARIABLE3 = Worksheets("sheet name").Range("J")
    VARIABLE4 = Worksheets("sheet name").Range("W")
    VARIABLE5 = Worksheets("sheet name").Range("G")
    VARIABLE6 = Worksheets("sheet name").Range("N")
    VARIABLE7 = Worksheets("sheet name").Range("X")
    VARIABLE8 = Worksheets("sheet name").Range("Y")
    VARIABLE9 = Worksheets("sheet2").Range("N7")

    Final_score = Score_calculations(VARIABLE1, VARIABLE2, VARIABLE3, VARIABLE4, VARIABLE5, VARIABLE6, VARIABLE7, VARIABLE8, VARIABLE9)
    Worksheets("sheet name").Range("Z").Value = Final_score
Next Row

2 个答案:

答案 0 :(得分:2)

首先不要使用Row作为变量。使用类似.Range("A")的内容。

然后将 .Cells(Rw.Row,"A") 更改为:

 .Range("A" & Rw.Row) 

为所有范围执行此操作。范围必须附加一行。

你也可以这样做:

Dim Rw as Range
Dim rng As Range
Dim Final_risk_score
Set rng = Worksheets("sheet name").Range("A1:Z100")

For Each Rw In rng.Rows
    VARIABLE1 = Worksheets("sheet name").Cells(Rw.Row,"A")
    VARIABLE2 = Worksheets("sheet name").Cells(Rw.Row,"K")
    VARIABLE3 = Worksheets("sheet name").Cells(Rw.Row,"J")
    VARIABLE4 = Worksheets("sheet name").Cells(Rw.Row,"W")
    VARIABLE5 = Worksheets("sheet name").Cells(Rw.Row,"G")
    VARIABLE6 = Worksheets("sheet name").Cells(Rw.Row,"N")
    VARIABLE7 = Worksheets("sheet name").Cells(Rw.Row,"X")
    VARIABLE8 = Worksheets("sheet name").Cells(Rw.Row,"Y")
    VARIABLE9 = Worksheets("sheet2").Range("N7")

    Final_risk_score= Score_calculations(VARIABLE1, VARIABLE2, VARIABLE3, VARIABLE4, VARIABLE5, VARIABLE6, VARIABLE7, VARIABLE8, VARIABLE9)
    Worksheets("sheet name").Cells(Rw.Row,"Z").Value = Final_risk_score
Next Row

所以:

{{1}}

答案 1 :(得分:1)

将循环更改为:

Dim myRow As Range
For Each myRow In rng.Rows
    With Worksheets("sheet name")

        VARIABLE1 = .Range("A" & myRow.Row)
        VARIABLE2 = .Range("K" & myRow.Row)
        'etc
    End With
Next Row

因此,只要您正确引用范围,它就会起作用。