VBA Excel 更改字段中的值

VBA Excel Change Value in Field

我有一个 excel table,其中有一列名为 "Completed?",用户从下拉列表中选择 select 是或否。如果他们 Select 是,则会弹出一个使用 vbOKCancel 的消息框。如果他们确认是,到目前为止该部分正在工作,但如果发生其他任何事情(他们点击取消或 X out 等),我希望将此字段更改为 "No" - 这就是我正在努力解决的问题。
看起来应该很简单 - 有什么想法吗?


If Target.Column = 3 And Target.Value = "Yes" Then

Dim answer As Integer
answer = MsgBox("Are you sure you want to mark this as Completed?  This will move the record to the Completed Tab and cannot be undone.", vbOKCancel + vbCritical, "CRITICAL WARNING")
If answer = vbOK Then MsgBox ("OK")

'need help with this next row
Else: Target.Value = "No"
End If

End Sub 


试试这个:

   If Target.Column = 3 And Target.Value = "Yes" Then

      Dim answer As Integer
      answer = MsgBox("Are you sure you want to mark this as Completed?  " & _
                     "This will move the record to the Completed Tab and cannot be undone.", vbOKCancel + vbCritical, "CRITICAL WARNING")

      If answer = vbOK Then
         MsgBox ("OK")

      Else
         Target.Value = "No"

      End If

   End If

从根本上说,您的问题是误用了 If Then Else End IF 结构。 (您正在混合使用多行和单行语法)

See here了解更多详情

还有一些其他问题,请参阅内联评论

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim answer As VbMsgBoxResult ' use correct data type
    Dim rng As Range, cl As Range

    On Error GoTo EH ' ensure events get turned back on

    Application.EnableEvents = False ' prevent event cascade
    Set rng = Application.Intersect(Target, Me.Columns(3)) ' get all cells in column 3 that changed
    For Each cl In rng ' process each changed cell
        If LCase(cl.Value) = "yes" Or LCase(cl.Value) = "y" Then  ' case insensitive
            answer = MsgBox("Are you sure you want to mark row " & cl.Row & " as Completed?" & vbNewLine & vbNewLine & "This will move the record to the Completed Tab and cannot be undone.", vbOKCancel + vbCritical, "CRITICAL WARNING")
            If answer = vbOK Then
                cl.Value = "Yes" ' Standardise case
                ' MsgBox "OK" ' this is a bit annoying
            Else
                cl.Value = "No"
            End If
        End If
    Next
EH:
    Application.EnableEvents = True
End Sub