我试图在一个范围内粘贴后插入一个列,然后用静态数据填充该新列。
我的内容似乎很接近,数据显示在工作表中,它会插入新列,直到我输入值“e1”。它在整个列中输入一个值,而不仅仅是范围,它正在替换第5列(“E”)数据而不是进入新列4(“D”)
Sub sbCopyRangeToAnotherSheet()
Dim SourceData As Worksheet
Dim DestinationData As Worksheet
Dim SourceRange1 As Range
Dim DestinationRange As Range
Dim ShiftRange As Range
Set SourceData = Sheets("is")
Set DestinationData = Sheets("reformatted")
Set SourceRange1 = SourceData.Range("A2", SourceData.Range("F1").End(xlDown))
Set DestinationRange = DestinationData.Range("A2", DestinationData.Range("G1").End(xlDown))
Set ShiftRange = DestinationData.Range("D2", DestinationData.Range("D2").End(xlDown))
' Run Group 1
SourceRange1.Copy Destination:=DestinationRange
ShiftRange.Insert Shift:=xlToRight
ShiftRange.Cells.Value = "e1"
'Application.CutCopyMode = False
End Sub
答案 0 :(得分:2)
Set ShiftRange = DestinationData.Range("D2", DestinationData.Range("D2").End(xlDown))
这将ShiftRange
定义为D列中的所有单元格,从D2开始向下,直到空单元格之前的最后一个单元格。
ShiftRange.Insert Shift:=xlToRight
现在已在ShiftRange
的左侧插入了一个单元格,因此ShiftRange
位于E列中。
ShiftRange.Cells.Value = "e1"
这将ShiftRange
(在E列中)中的所有单元格的值设置为" e1"。
它不会将所有列中的单元格设置为" e1"只是ShiftRange
中的单元格。但是,如果目标工作表的D3:D1048576中的所有单元格在复制之前都是空的,那么ShiftRange
将是D2:D1048576
,这将是几乎所有中的单元格列。
我想你想要
Sub sbCopyRangeToAnotherSheet()
Dim SourceData As Worksheet
Dim DestinationData As Worksheet
Dim SourceRange1 As Range
Dim DestinationRange As Range
Dim ShiftRange As Range
Set SourceData = Sheets("is")
Set DestinationData = Sheets("reformatted")
Set SourceRange1 = SourceData.Range("A2", SourceData.Range("F1").End(xlDown))
Set DestinationRange = DestinationData.Range("A2", DestinationData.Range("G1").End(xlDown))
' Run Group 1
SourceRange1.Copy Destination:=DestinationRange
'Define ShiftRange after the data has been placed in the destination sheet
Set ShiftRange = DestinationData.Range("D2", DestinationData.Range("D2").End(xlDown))
'Shift column D to column E
ShiftRange.Insert Shift:=xlToRight
'Insert values in column D
ShiftRange.Offset(0, -1).Value = "e1"
'Application.CutCopyMode = False
End Sub