EXCEL VBA 输入框确定/取消

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/16153481/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 15:28:16  来源:igfitidea点击:

EXCEL VBA InputBox Ok/Cancel

excelvba

提问by 4 Leave Cover

Basically I need 2 inputbox. First inputbox will ask user to input a value and then prompt the 2nd inputbox after user click ok. The default value in the 2nd inputbox will be the value one cell to the right of the value in the first inputbox. This is what I want to achieve but the problem with inputbox is that the Cancel button which throw me error message or won't exit sub by any means.

基本上我需要2个输入框。第一个输入框会要求用户输入一个值,然后在用户单击确定后提示第二个输入框。第二个输入框中的默认值将是第一个输入框中值右侧的一个单元格的值。这就是我想要实现的,但输入框的问题是取消按钮会抛出错误消息或不会以任何方式退出子程序。

So are there any other similar approaches in achieving my goal? Thanks a lot in advance!

那么还有其他类似的方法可以实现我的目标吗?非常感谢!

回答by James

InputBox(...)returns an empty string ""whenever the cancel button is pressed.

InputBox(...)""每当按下取消按钮时返回一个空字符串。

Knowing this, you could check to see if the input is ""for each input. If at any point along the way you encounter a cancel, you don't go any further.

知道了这一点,您可以检查输入是否""适用于每个输入。如果在此过程中的任何时候遇到取消,您就不会再继续了。

This is demonstrated below using nested if statements.

下面使用嵌套的 if 语句演示了这一点。

Sub Macro1()
    Dim x As String
    Dim y As String
    Dim yDefault As String

    x = InputBox("Prompt One", "TITLE ONE")

    If (x <> "") Then
            yDefault = GetDefaultValue(x)
            y = InputBox("Prompt Two", "TITLE TWO", yDefault)

        If (y <> "") Then
            MsgBox "X: " & x & vbCrLf & "Y: " & y, vbOKOnly, "RESULTS"
        End If
    End If
End Sub

Function GetDefaultValue(x As String) As String
    ' Your custom logic to grab the default value (whatever cell) goes here
    GetDefaultValue = "DEFAULT(" & x & ")"
End Function

回答by Siddharth Rout

Since it is the values that you want, don't use the InputBox. Use the Application.Inputbox. If you press the magic key F1in Excel and you type Application.Inputboxthen you will see some magic text appear out of nowhere ;)

因为它是您想要的值,所以不要使用InputBox. 使用Application.Inputbox. 如果您F1在 Excel 中按下魔法键并输入,Application.Inputbox那么您会看到一些魔法文本突然出现;)

Here is an example usage.

这是一个示例用法。

Ret = Application.InputBox(prompt := "Please enter a value", type := 1)

Notice the type 1.

注意类型1

I can give you an exact answer but I am sure this will get you started ;) If not then post back :)

我可以给你一个确切的答案,但我相信这会让你开始;) 如果没有,请回帖 :)