VBA Excel字段中的更改值

问题描述 投票:0回答:4

我有一个excel表,其中的列名为“已完成?”用户从下拉菜单中选择是或否。如果选择“是”,则会弹出一个使用vbOKCancel的消息框。如果他们确认“是”,则表示该部件到目前为止已经正常运行,但是如果发生其他任何事情(它们单击“取消”或X输出,等等),我希望将此字段更改为“否”,这就是我正在努力解决的问题。看起来应该很简单-有什么想法吗?


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 


excel vba msgbox
4个回答
0
投票

尝试一下:

   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

0
投票

您可能还希望在“是”中加入案例检查:

If Target.Column = 3 And LCase$(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
    Target.Value = "Yes"
    MsgBox ("OK")
  Else
    Target.Value = "No"
  End If
End If

0
投票

基本上,您发布的是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


-2
投票

也许您需要礼貌地向vba询问,因为它不是一种协作语言,所以只需在分配之前放置一个Set ...我永远都不知道何时需要它

Else
    Set Target.Value = "No"
End If
© www.soinside.com 2019 - 2024. All rights reserved.