2

我有一些 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

当我更新目标单元格时,我收到一条错误消息:“编译错误:未定义子或函数。”

谁能告诉我发生了什么事?

4

2 回答 2

0

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

而不是这个:

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

你应该试试这个

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

希望有效!

于 2013-07-04T06:28:17.357 回答
0

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

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

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
于 2013-07-03T20:13:06.790 回答