我以两种不同的方式尝试过这种方法。
首先,选择要复制的单元格范围,然后选择要粘贴的目标范围。以下是代码:
Sub PanelData()
Dim size As Integer
Dim i As Integer
Dim shrate As Worksheet
Dim shpanel As Worksheet
Set shrate = Sheets("Rate")
Set shpanel = Sheets("Panel")
size = shrate.Range("B4").End(xlDown).Row
shrate.Range(Cells(4, 2), Cells(size, 2)).Select
Selection.Copy
shpanel.Cells(1, 1).Value = size - 3
For i = 1 To 18
shpanel.Range(Cells(4, 1).Offset((i - 1) * (size - 3), 0), Cells(3, 1).Offset(i * (size - 3), 0)).Select
Selection.PasteSpecial Paste:=xlPasteValues
Selection.NumberFormat = "m/d/yyyy"
Next i
End Sub
其次,复制范围中的单元格,然后逐个粘贴到目标列。这是代码:
Sub LoopingCP()
Dim size As Integer
Dim shrate As Worksheet
Dim shpanel As Worksheet
Set shrate = Sheets(2)
Set shpanel = Sheets(4)
size = shrate.Cells(4, 2).End(xlDown).Row - 3
For x = 1 To 18
For i = 1 To size
shrate.Cells(i + 3, 2).Select
Selection.Copy
shpanel.Cells(x * (i + 3), 1).Select
Selection.PasteSpecial Paste:=xlPasteValues
Selection.NumberFormat = "m/d/yyyy"
Next i
Next x
End Sub
这些尝试都没有成功。我做错了什么?
由于
答案 0 :(得分:0)
有些事情妨碍了工作。首先,当使用Range变量时,例如Range()
,Cells()
,Rows()
,Columns()
等,您应始终明确表示你希望在那张纸上运行。
其次,您希望避免使用我在评论中链接的.Select
。实际上,您只需“备份”以.Select
/ .Selection
看看是否有效:
Sub PanelData()
Dim size As Integer
Dim i As Integer
Dim shrate As Worksheet
Dim shpanel As Worksheet
Set shrate = Sheets("Rate")
Set shpanel = Sheets("Panel")
size = shrate.Range("B4").End(xlDown).Row
shrate.Range(shrate.Cells(4, 2), shrate.Cells(size, 2)).Copy
shpanel.Cells(1, 1).Value = size - 3
For i = 1 To 18
With shpanel.Range(shpanel.Cells(4, 1).Offset((i - 1) * (size - 3), 0), shpanel.Cells(3, 1).Offset(i * (size - 3), 0))
.PasteSpecial Paste:=xlPasteValues
.NumberFormat = "m/d/yyyy"
End With
Next i
End Sub
Sub LoopingCP()
Dim size As Integer
Dim shrate As Worksheet
Dim shpanel As Worksheet
Set shrate = Sheets(2)
Set shpanel = Sheets(4)
size = shrate.Cells(4, 2).End(xlDown).Row - 3
For x = 1 To 18
For i = 1 To size
shrate.Cells(i + 3, 2).Copy
With shpanel.Cells(x * (i + 3), 1)
.PasteSpecial Paste:=xlPasteValues
.NumberFormat = "m/d/yyyy"
End With
Next i
Next x
End Sub
仅供参考 - 当您只想要这些值时,您可以将范围的值设置为彼此相等,而不是使用.Copy
/ .Paste
,这样可以避免使用剪贴板,并节省一点运行宏时的时间:
Range([destination range]).Value = Range([copy from range]).Value
(请注意,您需要在Range()
之前加入工作表名称。