我想在用户按下“ CommandButton1”后将所有输入数据复制到右侧单元格中 现在,我的代码可以复制输入,但是它将重复第一个输入单元格数据(如您在第一张图片中所见)
这是我的代码,仅复制第一个单元格值并将其重复作为输出(错误)
Private Sub CommandButton1_Click()
Dim wks As Worksheet
Dim AddNew As Range
Dim i As Integer, j As Integer
Set wks = Sheet1
Set AddNew = wks.Range("M65356").End(xlUp).Offset(2, 0)
For i = 1 To 15
For j = 0 To 6
AddNew.Offset(i, j).Value = Me.Range("B2:H16").Value
Next j
Next i
End Sub
答案 0 :(得分:0)
假设您的范围没问题。 (它与示例中的不匹配)。尝试以下一种方法:
For i = 1 To 15
For j = 0 To 6
AddNew.Offset(i, j).Value2 = Cells(i + 1,j + 1).Value2
Next j
Next i
如果您只想复制信息,然后删除输入区域中的前一个信息,只需添加:
For i = 1 To 15
For j = 0 To 6
AddNew.Offset(i, j).Value2 = Cells(i + 1,j + 1).Value2
Cells(i + 1,j + 1).Value2 =""
Next j
Next i
希望有帮助
答案 1 :(得分:0)
尝试以下代码:
Private Sub CommandButton1_Click()
' Don't use Integers, they are stored as Long anyway
Dim i As Long, j As Long
Dim wks As Worksheet
Set wks = Worksheets("Sheet1")
For i = 1 To 15
For j = 1 To 7
wks.Range("M4").Cells(i, j) = wks.Range("B2").Cells(i, j)
Next j
Next i
End Sub
只需将两个单元格(B2
和M4
)设置为要复制数据的范围的“锚”即可。然后,使用Cells
可以针对那些“锚”引用单元格(与使用Offset
十分相似)。
或者您可以更加简洁:
Private Sub CommandButton1_Click()
Dim wks As Worksheet
Set wks = Worksheets("Sheet1")
wks.Range("B2:H18").Copy wks.Range("M4")
End Sub