我有一个带有两个文本框的小用户窗体。我需要的是,当我按下提交按钮时,它将为我运行一个代码,最后它应该激活其名称在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 :(得分: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