创建新工作表,复制数据并命名工作表

时间:2018-04-18 14:17:52

标签: excel vba excel-vba range spreadsheet

我需要帮助!

我希望创建一个按钮,创建一个新工作表,复制已输入的数据,并将工作表命名为F5中输入的值。

到目前为止,我有这个:

Sub CreateNewSheet()
sheet_name_to_create = Sheet1.Range("F5").Value

For rep = 1 To (Worksheets.Count)
If LCase(Sheets(rep).Name) = LCase(sheet_name_to_create) Then
MsgBox "Already Exists!"
Exit Sub
End If
Next
Sheets.Add After:=Sheets(Sheets.Count)
Sheets(ActiveSheet.Name).Name = sheet_name_to_create

End Sub

这是为我创建新工作表,将其命名为F5中的值。 但我需要复制范围C4:G17

有人能帮助我吗?

由于

2 个答案:

答案 0 :(得分:0)

您可以尝试下一个代码:

Sub CreateNewSheet()
sheet_name_to_create = Sheet1.Range("F5").Value
Sheet1.Range("C4:G17").Copy 

For rep = 1 To (Worksheets.Count)
If LCase(Sheets(rep).Name) = LCase(sheet_name_to_create) Then
MsgBox "Already Exists!"
Exit Sub
End If
Next
Sheets.Add After:=Sheets(Sheets.Count)
Sheets(ActiveSheet.Name).Name = sheet_name_to_create
Sheets(sheet_name_to_create).Range("C4:G17").PasteSpecial xlPasteValues
End Sub

答案 1 :(得分:0)

试试这个:

Sub copy_newsheet()

Dim pname
Dim ws As Worksheet

pname = ActiveSheet.Range("F5").Value

For Each ws In ActiveWorkbook.Sheets

If ws.Name = pname Then
MsgBox "Already Exists"
Exit Sub
End If

Next ws

ActiveSheet.Range("C4:G17").Copy
Sheets.Add After:=ActiveSheet
ActiveSheet.Range("C4:G17").PasteSpecial Paste:=xlPasteValues
ActiveSheet.Range("C4:G17").PasteSpecial Paste:=xlPasteFormats
ActiveSheet.Name = pname

End Sub