无法使用列表框选择

时间:2017-04-08 10:23:17

标签: excel vba excel-vba

Code Page 2 Code Page 1我正在尝试使用列表框选择打开工作表。代码如下。但它显示错误。我是vba的新手。 Plz帮助

Public Sub AddData_Click()
Dim iRow As Long
Dim ws As Worksheet
Dim Sht As String
Sht.Text = ListBox1.SelectedItem.Tostring()
Worksheets(CStr(Sht)).Activate

2 个答案:

答案 0 :(得分:0)

试试这个

Private Sub AddData_Click()
Dim i As Integer
Dim sht As String
For i = 0 To ListBox1.ListCount - 1
    If ListBox1.Selected(i) Then
        sht = ListBox1.List(i)
    End If
Next i
If sht = "" Then
    MsgBox "You didn't select an item in the listbox.", vbExclamation
    Exit Sub
Else
    Worksheets(sht).Activate
End If
End Sub

答案 1 :(得分:0)

你可以试试这个:

Private Sub AddData_Click()    
    With Me.ListBox1
        If .ListIndex = -1 Then
            MsgBox "No item selected!"
        Else
            Worksheets(.Value).Activate
        End If
    End With
End Sub