【问题标题】:Using the input of inputbox in msgbox prompt在 msgbox 提示中使用 inputbox 的输入
【发布时间】:2018-10-13 05:21:32
【问题描述】:

我正在制作一个 InputBox,以便用户可以将他/她的名字用于 MsgBox。不是“hello user”,而是“hello (name)”。这是我的尝试。

Private Username As String
Username = InputBox(msg, "dear user")
InputBox msg, "dear user"
If Username = vbNullString Then
    Username = InputBox(msg, "dear user")
End If

我首先尝试制作输入框(它正在工作)。

Private Sub Workbook_open()

    Worksheets("Sheet1").Select

    Dim msg
    msg = "Please enter your name here"
    InputBox msg, "dear user"

End Sub

【问题讨论】:

    标签: excel vba


    【解决方案1】:

    欢迎来到 Stackoverflow。

    这是你正在尝试的吗?

    Sub Sample()
        Dim Ret As Variant
    
        Ret = InputBox("Please enter your name", "dear user")
    
        If Len(Trim(Ret)) <> 0 Then MsgBox "Hello " & Ret
    End Sub
    

    我尝试使用 urcode,但它似乎不起作用?我尝试将它放在工作表、模块和工作簿中,但什么也没有发生 D:哦,是的,我的目标是将输入框的输入用于我将在所有工作表中使用的所有 msgbox,首先说,如果文件打开,它会询问用户名;输入名称后,有一个消息框说“欢迎来到游戏”(或类似的东西)然后我的游戏有不同的表,如掷骰子,迷宫等,所以当用户转到表时,它欢迎他们再次通过 msgbox 并在游戏结束时祝贺他们 – Kurt Cinco 31 分钟前

    在这种情况下,您不应使用公共变量。出现错误时变量会重置。我建议将该名称保存到隐藏工作表中的单元格中。

    一个。添加工作表调用说Settings。隐藏工作表。

    B。在打开的工作簿中,粘贴此代码

    Private Sub Workbook_Open()
        Dim Ret As Variant
    
        Ret = InputBox("Please enter your name", "dear user")
    
        If Len(Trim(Ret)) <> 0 Then
            ThisWorkbook.Sheets("Settings").Range("A1").Value = Ret
            MsgBox "welcome to the game " & Ret
        End If
    End Sub
    

    C:在工作表代码中可以使用这个代码

    Sub Sample()
        Dim username As String
    
        username = ThisWorkbook.Sheets("Settings").Range("A1").Value
    
        MsgBox "Hello " & username
    End Sub
    

    【讨论】:

    • 我尝试使用 urcode,但它似乎不起作用?我尝试将它放在工作表、模块和工作簿中,但什么也没有发生 D:哦,是的,我的目标是将输入框的输入用于我将在所有工作表中使用的所有 msgbox,首先说,如果文件打开,它会询问用户名;输入名称后,有一个消息框说“欢迎来到游戏”(或类似的东西)然后我的游戏有不同的表,如掷骰子,迷宫等,所以当用户转到表时,它欢迎他们再次通过 msgbox 并在游戏完成时祝贺他们
    • 一会儿。更新帖子
    【解决方案2】:

    你可以设置一个ThisWorkbook对象属性

    将此代码放在ThisWorkbook 代码窗格中:

    Option Explicit
    
    Private mUserName As String
    
    Sub Workbook_Open()
        mUserName = InputBox("Please enter your name", "dear user")
    End Sub
    
    Public Property Get MyUserName() As String
        MyUserName = mUserName
    End Property
    

    现在您可以通过简单的编码从任何普通模块和/或工作表模块访问

    MsgBox "hello " & ThisWorkbook.MyUserName
    

    作为一种可能的增强功能,您可以通过适当调整 Workbook_Open() sub 来强制用户输入一些有效名称,例如:

    Sub Workbook_Open()
        Do
             mUserName = InputBox("Please enter your name", "dear user")
        Loop While mUserName = vbNullString
    End Sub
    

    【讨论】:

      猜你喜欢
      • 2021-06-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-01-08
      • 1970-01-01
      • 2010-10-10
      • 2012-12-17
      相关资源
      最近更新 更多