如何从用户窗体中检索值

how to retrieve a value from an userform

我正在尝试编写代码来跟踪用户在任何工作表上所做的每一次更改。用户将输入数据并时不时地擦除所述数据and/or 更正他们插入的原始值。如果更改是删除或修改,将弹出一个用户表单,用户将包括更改的原因。现在,每当用户进行前面提到的其中一项更改时,我都能显示表单,但我无法检索原因,你们能帮帮我吗?

这就是我的用户表单

Private Sub CommandButton1_Click()
Dim msgvalue As VbMsgBoxResult
Dim value As String
msgvalue = MsgBox("Do you wish to save the change?", vbYesNo + vbInformation, "Confirm")
    If msgvalue = vbNo Then GoTo Command 
    If msgvalue = vbYes Then
        value = UserForm1.txtCmmt.Value
        If value = "" Then GoTo Command
        End
    End If
Command:
MsgBox ("A reason must be provided")
    With UserForm1
        .txtCmmt.Value = ""
    End With
End Sub

所以如果用户试图删除一个值,代码如下:

Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)

Dim sLastAction As String
Dim Cell As Range
sLastAction = Application.CommandBars("Standard").Controls("&Undo").List(1)
For Each Cell In Target
    If sLastAction = "Clear" Or sLastAction = "Delete" Or Left(sLastAction, 9) = "Typing ''" Then
       
        UserForm1.Show 'this is where I'm stuck, I'm not sure how to retrieve the value from the form
    End If
'the code continues to retrieve other info from the changes made, including the "reason"

感谢您的帮助!

请尝试下一种方式:

  1. 假设您要写入评论的文本框名为“txtComment”。
  2. 将此代码放入其 Exit 事件中:
Private Sub txtComment_Exit(ByVal Cancel As MSForms.ReturnBoolean)
 If Me.txtComment.text <> "" Then
    If ActiveSheet.Name <> "LogDetails" Then
        Application.EnableEvents = False
         Sheets("LogDetails").Range("A" & rows.count).End(xlUp).Offset(0, 5).Value = Me.txtComment.text
        Application.EnableEvents = True
        Unload Me
    End If
 End If
End Sub

让现有的 Worksheet_Change 事件保持原样,只启动表单并可能创建一个 Public 布尔变量(来自标准模块)True(某事 boolStop) 不允许更改任何工作表中的任何内容,直到它不是 False.

然后在文本框中填写您需要的文本(“txtComment”,或者您命名的任何名称)并按 Enter。如果我上面的建议对你来说很有趣,那么文本框事件的最后一行将是 boolStop = False.

如果您了解如何实施上述简单解决方案,您可能会忘记用户表单并使用简单的 InputBox,如下例所示:

Private Sub Worksheet_Change(ByVal Target As Range)
    If Target.Address(0, 0) <> "E1" Then Exit Sub
    Dim sLastAction As String, comValue As String
    Dim Cell As Range
    sLastAction = Application.CommandBars("Standard").Controls("&Undo").list(1)
    For Each Cell In Target
        If sLastAction = "Clear" Or sLastAction = "Delete" Or left(sLastAction, 9) = "Typing ''" Then
WritePlease:
            comValue = InputBox("Please write the reason for cell """ & Cell.Address & """ (" & sLastAction & ").", "Reason, please")
              If comValue = "" Then GoTo WritePlease
              If ActiveSheet.Name <> "LogDetails" Then
                  Application.EnableEvents = False
                    'Stop
                   Sheets("LogDetails").Range("A" & rows.count).End(xlUp).Offset(0, 5).Value = comValue
                  Application.EnableEvents = True
              End If
        End If
    Next
End Sub