组合框文本不在列表错误处理VBA

时间:2016-08-31 08:51:00

标签: excel vba excel-vba combobox

我有一张大约130页的工作簿,我从主页上的组合框中选择。我使用rowsource填充组合框,来自命名范围,其中包含工作表名称。如果您从列表中选择一个工作表名称,它会很有效,如果您没有输入任何内容并且仍按提交,它会很好地关闭。我想要介绍用户输入不在列表中的内容的情况。我想对VBA说'如果sWs不等于命名范围内的东西,然后显示一个显示'错误'的消息框,或者其他什么。以下是我的代码,附注:

'if submit button is pressed go to selected worksheet or close the userform:
   Private Sub Submit_Click()
   Dim sWs As String
   'the string is the text from combobox, called 'Title', selected on front page:
   sWs = Me.Title.Value
      'if nothing is selected then close the userform:
      If sWs = ("") Then
      End
      End If
      'If an item is selected from the dropdown list then show that worksheet and close the userform:
      Worksheets(sWs).Select
      End
      End Sub

'If exit button is pressed close the userform:
   Private Sub ExitButton_Click()
   End 
   End Sub

我想我需要使用布尔值,所以我可以指定当它为假时要做什么,但不知道如何写它。对不起,我有点像菜鸟。

有什么想法吗?

1 个答案:

答案 0 :(得分:0)

尝试检查所选项目的列表索引,-1表示输入的内容无效

'if submit button is pressed go to selected worksheet or close the userform:

   Private Sub Submit_Click()
   Dim sWs As String

   'the string is the text from combobox, called 'Title', selected on front page: 
   If Me.Title.ListIndex = - 1 Then
     MsgBox "Invalid Entry"
     End
   End If

      sWs = Me.Title.Value

      'if nothing is selected then close the userform:
      If sWs = ("") Then
      End
      End If

      'If an item is selected from the dropdown list then show that worksheet and close the userform:
      Worksheets(sWs).Select
      End
      End Sub

'If exit button is pressed close the userform:
   Private Sub ExitButton_Click()
   End 
   End Sub