繁体   English   中英

使用文本框选择工作表的代码

[英]Code to Select the Worksheet using textbox

我有一个小的用户窗体,其中有两个文本框。 我需要的是,当我按下“提交”按钮时,它将为我运行一个代码,最后它应激活其工作表,该工作表的名称输入到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

请帮我。

感谢Salman Khan

如果您引用宏所在的同一工作簿中的工作表,则应使用

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM