vba .cells.value应用程序定义或用户定义的错误

时间:2015-10-16 10:56:45

标签: vba excel-vba runtime-error excel

我使用以下代码计算工作表每行中组合的出现次数:

  

0

     

1

然而,行.Cells(r + 1, c).Value = activation_count导致运行时错误1004:应用程序定义或用户定义错误

任何人都可以看到问题的来源吗?

Sub count_activations() 'to count 01 combinations in sheet

Dim row As Long
Dim col As Long
Dim r As Long
Dim c As Integer
Dim activation_count As Integer

    With Sheets("Link_TSR 10yr_Year 1_RTC1 Whitl")

        row = Range("A:A").Rows.Count
        col = .Cells(1, Columns.Count).End(xlToLeft).Column

        For c = 3 To col 
            activation_count = 0

                For r = 4 To row

                    If Cells(r, c).Value = 0 And Cells(r - 1, c).Value = 1 Then
                    activation_count = activation_count + 1
                    End If
                Next r
                    .Cells(r + 1, c).Value = activation_count
        Next c

    End With

End Sub

谢谢

1 个答案:

答案 0 :(得分:0)

道歉我忘了早点发布更正后的代码。

以前,我正在计算工作表中我想用数据计算所有行的所有行。干杯Davesexcel指出明显的错误!

 Sub count_activations() 'to count 01 combinations in sheet

    Dim row As Long
    Dim col As Long
    Dim r As Long
    Dim c As Integer
    Dim activation_count As Integer

        With Sheets("Link_TSR 10yr_Year 1_RTC1 Whitl")
        row = .Cells(.Rows.Count, "A").End(xlUp).row 'counts only the used cells in column A
        col = .Cells(1, Columns.Count).End(xlToLeft).Column
    For c = 3 To col 
        activation_count = 0

            For r = 4 To row

                If Cells(r, c).Value = 0 And Cells(r - 1, c).Value = 1 Then
                activation_count = activation_count + 1
                End If
            Next r
                .Cells(r + 1, c).Value = activation_count
        Next c

    End With

End Sub