修改VBA代码以分别更改每一行的单元格输入

时间:2019-12-12 19:10:56

标签: excel vba

我已经对此进行了一段时间的故障排除,并被卡住了……我希望它逐行运行,当F到L时,列F到L乘以D列中的值。输入号码。有什么建议么? (我不是一个好的程序员,但是真的希望我的电子表格中有此功能!)谢谢!

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim rng As Range
    Dim row As Range
    Dim cell As Range
    Dim rate As Double

    Set rng = Application.Intersect(Target, Me.Range("D74:L200"))

    If Not rng Is Nothing Then
        Application.EnableEvents = False
        for Each row In rng.Rows
            rate = row.Columns.Item(0).Value
            For Each cell In row.Cells
                cell.Value = cell.Value * rate
            Next cell
        Next row
        Application.EnableEvents = True
    End If

End Sub

1 个答案:

答案 0 :(得分:1)

请注意,我将使用与row不同的变量名,因为这可能会造成混乱。

如果在该范围内输入非数字输入,还可以添加一些错误处理:

Private Sub Worksheet_Change(ByVal Target As Range)

    Dim rng As Range
    Dim rw As Range
    Dim cell As Range
    Dim rate As Double

    Set rng = Application.Intersect(Target, Me.Range("F74:L200"))

    If Not rng Is Nothing Then
        On Error GoTo SafeExit
        Application.EnableEvents = False
        For Each rw In rng.Rows
            rate = Me.Cells(rw.Row, "D").Value

            For Each cell In rw.Cells
                cell.Value = cell.Value * rate
            Next
        Next
    End If

SafeExit:
    Application.EnableEvents = True
End Sub