2015-10-23 76 views
0

我正在嘗試創建一個簡單的註冊系統。爲此,我創建了一個包含一個ComboBox和四個TextBox的用戶窗體。在ComboBox中的選擇應該選擇在哪個工作表中保存數據。該錯誤代碼是:通過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 
+0

其中你遇到的問題是什麼? – tguzella

+0

首先設置變量然後使用它: sheet = ComboBox1.Value 設置ws =工作表(「工作表」) 工作表(「工作表」)。選擇 – Fabrizio

+0

您在說'sheet'是工作表,然後嘗試說它等於'ComboBox1.Value' – Calum

回答

0

如果我理解正確的話,或許下面是你想要什麼:

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

與原來的問題代碼是指定後的變量sheet,從不使用,選擇工作表等。