我想接受一位数字的用户输入,并使用它来复制许多行,即userinput = n-> rows(1:n)。如果用户输入范围,我就成功复制了范围:
Set rng = Application.InputBox("mytext", Type:=8)
但是我需要通过提供一个数字来做到这一点,因为我的同事不能在希望的行数之前写“ 1:”。我的完整代码如下。
提前谢谢
Private Sub CommandButton21_Click()
Dim rng As Range
Worksheets("Sheet2").Activate
Set rng = Application.InputBox("mytext", Type:=8)
If Not rng Is Nothing Then Set rng = rng.EntireRow
rng.Copy
Worksheets("Sheet1").Activate
Worksheets("Sheet1").Range("A1").Rows("9").Select
Selection.Insert Shift:=xlDown
Range("A1").Rows("9").PasteSpecial xlPasteFormats
End Sub
答案 0 :(得分:1)
这是验证输入框条目的一种方法。以下代码仅允许输入数字,且输入范围必须为1-9。其他任何内容将显示MsgBox
和Exit Sub
Option Explicit
Sub test()
Dim n As Integer
n = Application.InputBox("Enter # 1 - 9", Type:=1)
If n > 9 Then
MsgBox "Entry Larger than 9. Please try again"
Exit Sub
ElseIf n < 1 Then
MsgBox "Entry less than 1. Please try again"
Exit Sub
End If
'Your code goes here once all validatoins are complete
End Sub
答案 1 :(得分:0)
如果您想要从用户那里获得一位数字,@ udearboy的另一个答案将满足您的期望,但是如果我正确理解并且您希望最终用户给您最后要复制的行那么以下将为您实现:
Private Sub CommandButton21_Click()
Dim ws1 As Worksheet: Set ws1 = ThisWorkbook.Worksheets("Sheet1")
Dim ws2 As Worksheet: Set ws2 = ThisWorkbook.Worksheets("Sheet2")
'declare and set the worksheets you are working with
ws2.Activate
n = Application.InputBox("Enter the number for the last row to copy:", Type:=1)
'get input from user
If IsNumeric(n) Then 'check if input is numeric
ws2.Range("1:" & n).EntireRow.Copy 'copy range
ws1.Range("A1").Rows("9").Insert Shift:=xlDown 'insert the values
ws1.Range("A1").Rows("9").PasteSpecial xlPasteFormats 'copy formats
ws1.Activate
End If
End Sub
更新:
我对代码进行了少许修改,以检查用户输入的值是否为整数并且大于0,因此由于输入的值不正确,您应该会遇到任何错误,我可能还会检查输入的值在工作表上的数据范围内,但我没有在下面添加它:
Private Sub CommandButton21_Click()
Dim ws1 As Worksheet: Set ws1 = ThisWorkbook.Worksheets("Sheet1")
Dim ws2 As Worksheet: Set ws2 = ThisWorkbook.Worksheets("Sheet2")
'declare and set the worksheets you are working with
ws2.Activate
n = Application.InputBox("Enter the number for the last row to copy:", "Please enter a Number", Type:=1)
'get input from user
If (IsNumeric(n)) And (CDbl(n) - CInt(n) = 0) And (n > 0) Then
'check if input is numeric and a whole number and greater than 0
ws2.Range("1:" & n).EntireRow.Copy 'copy range
ws1.Range("A1").Rows("9").Insert Shift:=xlDown 'insert the values
ws1.Range("A1").Rows("9").PasteSpecial xlPasteFormats 'copy formats
ws1.Activate
Else
MsgBox "Please enter a whole number greater than 0", vbCritical, "Error"
End If
End Sub