我正在尝试编写一个循环,它将使我的代码获取用户在单元格“C4”中输入的数字,并将该值粘贴到单元格“C10”中。用户输入的任何新数字也应粘贴在单元格“C10”下。我被困在这段代码的底部“For i = ..”非常感谢任何帮助
Public Sub Sheet1()
Application.OnKey "{ENTER}", "EnterANumber"
End Sub
Sub EnterANumber()
If Range("C4").Value < 10 Then
MsgBox ("The number you entered is less than 10")
Else
If Range("C4").Value > 10 Then
MsgBox ("The number you entered is greater than 10")
Else
If Range("C4").Value = 10 Then
MsgBox ("The number you entered is 10!")
End If
End If
End If
'copy the number from cell c4 and place it into cell c10
Range("C4").Select
Selection.Copy
Range("C10").Select
ActiveSheet.Paste
'copy the number from C10 and place it in C11. Any new number after that place in C12,C13,C14,etc.
For i = 1 To 100
Selection.Copy
ActiveCell.Offset(1, 0).Select
ActiveSheet.Paste
Next i
End Sub
答案 0 :(得分:0)
这是一个使用工作表事件过程的替代方法,它看起来比使用onKey事件更方便 - 我刚刚跳过消息框部分。如果您尝试一下,请不要忘记将其放在工作表代码模块中。
请注意,此代码使用了Range对象的不受欢迎的End()方法 - 但在此上下文中似乎是合适的。
Private Sub Worksheet_Change(ByVal Target As Range)
Dim outputCell As Range
If Not intersect(Target, Range("C4")) is Nothing Then
With Range("C10")
If IsEmpty(.Value) Or IsEmpty(.Offset(1, 0).Value) Then
Set outputCell = IIf(IsEmpty(.Value), .Item(1), .Offset(1, 0).Item(1))
Else
Set outputCell = .End(xlDown).Offset(1, 0)
End If
End With
outputCell.Value = Range("C4").Value
End If
End Sub
答案 1 :(得分:-1)
我修改了你的代码如下:
Public Sub Sheet1()
Application.OnKey "{ENTER}", "EnterANumber"
End Sub
Sub EnterANumber()
If Range("C4").Value < 10 Then
MsgBox ("The number you entered is less than 10")
End If
If Range("C4").Value > 10 Then
MsgBox ("The number you entered is greater than 10")
End If
If Range("C4").Value = 10 Then
MsgBox ("The number you entered is 10!")
End If
If Range("C10").Value = "" Then
RowNo = 10
Else
RowNo = Range("C10").CurrentRegion.Rows.Count + Range("C10").Row
End If
Range(Cells(RowNo, 3), Cells(RowNo, 3)).Value = Range("C4").Value
End Sub