如何使用input框复制单元格区域并粘贴到新创build的表单

这是我第一次在这里,需要一些帮助。 我刚刚在YouTube的帮助下开始编码,这不太合适。 我在这里看到一个post,可以帮助您使用VBA创build工作表。 而这正是我开始的。 也许你可以帮我一路。

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 

试试像这样…

 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 

一个问题在这里:

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

你需要计算出这个范围,但是把它放在引号里,就像你说的那样。 尝试这个:

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

另一个问题在这里:

 activeheet.Paste 

你拼错了ActiveSheet。 尝试:

 ActiveSheet.Paste 

最好远离SelectSelectionActiveSheet ,而是使用完全限定的RangeWorksheets对象。

在这里阅读如何避免使用在Excel VBA中select 。

另外,剪切>>粘贴是单行语法(参见下面的代码),只是尽量保持2行为尽可能接近(在此操作之前创build新的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 

input框types8可以用于此目的,因为它允许用户select所需的范围。

你可能会在这里find其他的例子。

克里斯