How to fix “Run time error '-2147417848(80010108) Method 'Range' of Object _ Worksheet' Failed” caused by code within a worksheet

匆匆过客 提交于 2021-02-11 12:22:33

问题


I'm writing a code that calculate number automatically every time you edit a sheet. But somehow the code I wrote is not functioning properly that it gives a run-time error. I checked the cells and range but they are all valid and correct. All of the inputs and variables involved are simple integers (no more than 3 digits).

I just got a work assignment to automate some excel sheets at work and I just learned vba from ground up recently.

Private Sub Worksheet_Change(ByVal Target As Range)


Dim A As Integer
Dim i As Byte

i = 5

For i = 5 To 12

    If Worksheets("Sheet1").Range("D" & i).Value = "" Or Worksheets("Sheet1").Range("D" & i).Value = 0 Then

            A = Worksheets("Sheet1").Range("E" & i).Value - Worksheets("Sheet1").Range("C" & i).Value

            Worksheets("Sheet1").Range("F" & i).Value = A

    Else
            Worksheets("Sheet1").Range("F" & i).Value = Worksheets("Sheet1").Range("D" & i).Value * Worksheets("Sheet1").Range("B" & i).Value _
            + Worksheets("Sheet1").Range("E" & i).Value - Worksheets("Sheet1").Range("C" & i).Value

    End If

Next i

End Sub

It gives a run-time error


回答1:


Give this a shot and let me know what error you get:

Private Sub Worksheet_Change(ByVal Target As Range)

    'Only run if something changes in column D or E
    If Target.Column = 4 Or Target.Column = 5 Then

        'Turn off any events so that we don't encounter recursion
        Application.EnableEvents = False

        'This will help readability a bit
        Dim sht As Worksheet
        Set sht = ThisWorkbook.Worksheets("Sheet1")

        Dim A As Integer
        Dim i As Long

        'This needs to be removed - it's irrelevant as i is used as an iterable on the next line
        'i = 5

        For i = 5 To 12

            If sht.Range("D" & i).Value = "" Or sht.Range("D" & i).Value = 0 Then
                'What's the point of using a variable here?
                A = sht.Range("E" & i).Value - sht.Range("C" & i).Value
                sht.Range("F" & i).Value = A
            Else
                'Order of operations - is that important here?
                'Are we certain these fields are numeric?
                sht.Range("F" & i).Value = sht.Range("D" & i).Value * sht.Range("B" & i).Value _
                + sht.Range("E" & i).Value - sht.Range("C" & i).Value
            End If

        Next i

        'Turn it back on once we're done
        Application.EnableEvents = True

    End If

End Sub


来源:https://stackoverflow.com/questions/57116941/how-to-fix-run-time-error-214741784880010108-method-range-of-object-wor

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!