如何使用输入框复制单元格范围并粘贴到新创建的工作表

时间:2017-07-30 07:50:39

标签: excel vba excel-vba

这是我第一次来这里需要一些帮助。因为我刚开始在youtube的帮助下编码不好。我在这里看到一篇文章,可以帮助您使用VBA创建工作表。这就是我开始的。你可以帮我一路走来。

Sub cutcell()

Dim number, name As Variant

'ask the number of cell and name of new sheet

number = InputBox("Number of cells to cut")
name = InputBox("Name of new sheet")

' select Cell from A1 to the number of sheet inputted
Range("A1:A(number)").Select
Selection Cut

'creates a new worksheet
Sheets.Add After:=Sheets(Sheets.Count)
Sheets(Sheets.Count).name = name.Value ' renames the new worksheet
Range("A1").Select
activeheet.Paste

End Sub

4 个答案:

答案 0 :(得分:1)

尝试这样......

Sub cutcell()
Dim wsNew As Worksheet
Dim RngToCut As Range
Dim number, NewName As Variant

Application.ScreenUpdating = False

'ask the number of cell and name of new sheet
number = Application.InputBox("Number of cells to cut", Type:=1)    'This will only allow a number input

If number = 0 Then
    MsgBox "You didn't enter  number.", vbCritical
    Exit Sub
End If

Set RngToCut = Range("A1:A" & number)

'Ask user to input name of the New Sheet
NewName = InputBox("Name of new sheet")

If NewName = "" Then
    MsgBox "You didn't input the name of New Sheet.", vbCritical, "New Sheet Name Missing!"
    Exit Sub
End If

Set wsNew = Sheets.Add(After:=Sheets(Sheets.Count))
wsNew.name = NewName

RngToCut.Cut wsNew.Range("A1")
Application.ScreenUpdating = True
End Sub

答案 1 :(得分:0)

这里有一个问题:

Range("A1:A(number)").Select

你需要计算出范围,但是把它放在引号中就像字面意思一样。试试这个:

Range("A1:A" + number).Select

另一个问题是:

activeheet.Paste

你拼错了ActiveSheet。尝试:

ActiveSheet.Paste

答案 2 :(得分:0)

如果您远离SelectSelectionActiveSheet,最好使用完全限定的RangeWorksheets个对象。

请阅读How to avoid using Select in Excel VBA

此外,剪切>>粘贴是一行语法(请参阅下面的代码),只是尽量保持2个操作尽可能接近(在此操作之前创建新的Worksheet对象)。

<强> 代码

Option Explicit

Sub cutcell()

Dim number As Long, name As String
Dim OrigSht As Worksheet
Dim NewSht As Worksheet

'ask the number of cell and name of new sheet
number = InputBox("Number of cells to cut")
name = InputBox("Name of new sheet")

' save the currebt active sheet
Set OrigSht = ActiveSheet ' <-- I still prefer to use Worksheets("SheetName")

' first create the new worksheet
Set NewSht = Sheets.Add(After:=Sheets(Sheets.Count))
NewSht.name = name ' renames the new worksheet

' select Cell from A1 to the number of sheet inputted , use Cut>>Paste in 1 line
OrigSht.Range("A1:A" & number).Cut Destination:=NewSht.Range("A1")

End Sub

答案 3 :(得分:0)

输入框类型8可用于此目的,因为它允许用户选择所需的范围。

您可以在此处找到其他示例。

克里斯