通过ComboBox激活其他工作表

时间:2015-10-23 09:44:56

标签: excel vba excel-vba combobox worksheet

我正在尝试创建一个简单的注册系统。为此,我创建了一个userform,包括一个ComboBox和四个TextBoxes。 ComboBox中的选择应该选择保存数据的工作表。错误代码是:

 Set ws = Worksheets("sheet")
    sheet = ComboBox1.Value
    Worksheets("sheet").Select

我的总体VBA代码为:

Private Sub CommandButton1_Click()

Dim iRow As Long
Dim ws As Worksheet
Dim sheet As String


Set ws = Worksheets("sheet")
sheet = ComboBox1.Value

Worksheets("sheet").Select



' Verify if First Name is available
If Trim(Me.TextBox1.Value) = "" Then
    Me.TextBox1.SetFocus
    MsgBox "Voornaam ontbreekt"
    Exit Sub
End If

' Verify if Last Name is available
If Trim(Me.TextBox2.Value) = "" Then
    Me.TextBox2.SetFocus
    MsgBox "Achternaam ontbreekt"
    Exit Sub
End If

' Verify if Klasse is available
If Trim(Me.ComboBox1.Value) = "" Then
    Me.ComboBox1.SetFocus
    MsgBox "Klasse ontbreekt"
    Exit Sub
End If

' Verify if Paard is available
If Trim(Me.TextBox4.Value) = "" Then
    Me.TextBox4.SetFocus
    MsgBox "Naam paard ontbreekt"
    Exit Sub
End If


'find first empty row in database
iRow = ws.Cells(Rows.Count, 1).End(xlUp).Offset(1, 0).Row

'copy the data to the database
ws.Cells(iRow, 1).Value = Me.TextBox1.Text
ws.Cells(iRow, 2).Value = Me.TextBox2.Text
ws.Cells(iRow, 3).Value = Me.ComboBox1.Text
ws.Cells(iRow, 4).Value = Me.TextBox4.Text
ws.Cells(iRow, 5).Value = Me.TextBox5.Text

'clear the data in all textbox

Dim ctl
For Each ctl In Me.Controls
If TypeOf ctl Is MSForms.TextBox Then
    ctl.Text = ""
End If

Next ctl

End Sub



Private Sub UserForm_Initialize()
With ComboBox1
.AddItem "0,80 m"
.AddItem "0,90 m"
.AddItem "1 m"
.AddItem "1,10 m"
.AddItem "1,20 m"
.AddItem "1,30 m"
End With

End Sub

1 个答案:

答案 0 :(得分:0)

如果我理解正确,也许以下是你想要的:

sheet = ComboBox1.Value
Set ws = Worksheets(sheet)
ws.Select

原始代码的问题在于,从未使用过分配后的变量sheet来选择工作表等。