在VBA中使进程在多行中工作

时间:2013-07-03 19:57:52

标签: excel vba excel-vba

我有一些VBA代码,它根据前一个单元格的值更新许多单元格的值。目前,我可以让它为一行信息工作。但是,我希望它可以用于多行。我一直在编写和复制+粘贴代码片段,所以很有可能它只是缺乏连贯性。

Private Sub Worksheet_Change(ByVal Target As Range)
Dim rwIndex As Integer
For rwIndex = 4 To 400
If Target.Address = Cells(rwIndex, 3) Then

    If Range(Target.Address).Value = "Intrinsic" Then
        Dim LYVMessage
        LYVMessage = "Enter Last Year's Value"
        Cells(rwIndex, 5).Value = InputBox(LYVMessage)
    Else
        Cells(rwIndex, 5).Value = "NA"
        Cells(rwIndex, 6).Value = "NA"
        Cells(rwIndex, 9).Value = "NA"
        Cells(rwIndex, 10).Value = "NA"
        Cells(rwIndex, 11).Value = "NA"
        Cells(rwIndex, 12).Value = "NA"
        Cells(rwIndex, 7).Value = "NA"
        Cells(rwIndex, 8).Value = "NA"
        QMessage = "Enter whether Quantity is a Fixed Variable (1) or Random Variable (Logistic or Triangular)"
        Cells(rwIndex, 13).Value = InputBox(QMessage)
        PMessage = "Either Enter a Fixed Value for Price, or Enter Whether it is a Random Variable (Logistic or Triangular)"
        Cells(rwIndex, 14).Value = InputBox(PMessage)
    End If
End If
Next rwIndex
End Sub

当我更新目标单元格时,出现错误,上面写着:“编译错误:Sub或Function未定义。”

谁能告诉我发生了什么?

2 个答案:

答案 0 :(得分:0)

几个问题:它不是“细胞”而是“细胞”。此代码也需要在工作表的代码中,而不是在模块中。 并且它不会做任何事情......

这是一个应该按照我的理解你想做的代码:如果修改第4行和第400行之间的“C”列中的单元格,则更改值

Private Sub Worksheet_Change(ByVal Target As Range)

Application.ScreenUpdating = False ' Turn screen updating off
Application.EnableEvents = False  ' Turn the events off to avoid trigerring this macro within this macro when changing cell values

Dim r As Integer, c As Integer
Dim Message As String

' Get the Target cell's row and column (the cell you just modified and that triggered this macro)
r = Target.Row
c = Target.Column

' If the target cell is in column 3 and between rows 4 and 400 included
If c = 3 And (r > 3 And r < 401) Then

    If Target.Value = "Intrinsic" Then

        Message = "Enter Last Year's Value"
        Cells(r, 5).Value = InputBox(Message)

    Else
        Cells(r, 5).Value = "NA"
        Cells(r, 6).Value = "NA"
        Cells(r, 9).Value = "NA"
        Cells(r, 10).Value = "NA"
        Cells(r, 11).Value = "NA"
        Cells(r, 12).Value = "NA"
        Cells(r, 7).Value = "NA"
        Cells(r, 8).Value = "NA"

        Message = "Enter whether Quantity is a Fixed Variable (1) or Random Variable (Logistic or Triangular)"
        Cells(r, 13).Value = InputBox(Message)

        Message = "Either Enter a Fixed Value for Price, or Enter Whether it is a Random Variable (Logistic or Triangular)"
        Cells(r, 14).Value = InputBox(Message)

    End If

End If

' Turn events and screen updating back on
Application.EnableEvents = True
Application.ScreenUpdating = True

End Sub

答案 1 :(得分:0)

在代码的第4行中,您将目标单元格(字符串)的地址与单元格(范围)进行比较。

而不是:

If Target.Address = Cells(rwIndex, 3) Then

你应该试试这个

If Target.Address = Cells(rwIndex, 3).Address Then

希望有效!!!