2016-03-12 33 views
0

我有一個帶有兩個文本框的小型用戶窗體。我需要的是,當我按下提交按鈕時,它會爲我運行一個代碼,最後它應該激活名稱在textbox2中輸入的工作表。到目前爲止,我已經經歷了所有階段,但無法完成最後一步。使用文本框選擇工作表的代碼

這裏是我的代碼:

Private Sub CommandButton1_Click() 
'Defining the Variables 
Dim ws As Worksheet 
Dim tbl As ListObject 
Dim row As ListRow 
Dim sample As Worksheet 

'Assigning the Variables 
Set ws = UserForm2.txt2.Value 
Set tbl = ws.ListObjects(1) 
Set row = tbl.ListRows.Add(Alwaysinsert:=True) 

'Setting Up the Range and Enter Data in Table 
lastrow = ws.Range("A:A").End(xlUp).row 
row.Range(1, 1).Value = txt1.Value 

'Create the New Sheet for the Account Head Created 
Sheets("Summary-CH-Sample").Copy After:=Sheets(Sheets.Count) 
Set sample = ActiveSheet 
sample.Name = UserForm2.txt1.Value 

'Entering the Sheet name in Newly Created Sheet 
With ActiveSheet 
Range("A7").Value = "Summary of " & UserForm2.txt1.Value 
End With 

請幫助我。

感謝 薩爾曼·汗

回答

0

如果你指的是在隨後的宏所在的同一工作簿中工作,你應該使用

Set ws = ThisWorkbook.Worksheets(UserForm2.txt2.Value) 

這裏與其他一些小建議沿着陳述你的代碼

Option Explicit 

Private Sub CommandButton1_Click() 

'Defining the Variables 
Dim ws As Worksheet 
Dim tbl As ListObject 
Dim row As ListRow 
Dim sample As Worksheet 
Dim lastrow As Long 

Dim txt1Val As String, txt2Val As String '<== use variables to collect data from UserForm, to avoid multiple references to objects 

With Me ' thus referring to UserForm2 
    txt1Val = .txt1.Value 
    txt2Val = .txt2.Value 
End With 

'Assigning the Variables 
Set ws = ThisWorkbook.Worksheets(txt2Val) '<== 
Set tbl = ws.ListObjects(1) 
Set row = tbl.ListRows.Add(Alwaysinsert:=True) 

'Setting Up the Range and Enter Data in Table 
With ws 
    lastrow = .Cells(.Rows.Count, 1).End(xlUp).row '<== but where do you use it? 
End With 

row.Range(1, 1).Value = txt1Val ' <== 

'Create the New Sheet for the Account Head Created 
ThisWorkbook.Sheets("Summary-CH-Sample").Copy After:=Sheets(Sheets.Count) '<== always specify the workbook you want to work with. here I specified ThisWorkbook. myabe you want ActiveWorkbook 
Set sample = ActiveSheet 
sample.name = txt1Val 

'Entering the Sheet name in Newly Created Sheet 
With ActiveSheet 
    Range("A7").Value = "Summary of " & txt1Val 
End With 


End Sub 
相關問題