我试图将指定的愤怒从一个工作簿粘贴到另一个工作簿,我指定的范围称为SourceRange,其目标是TargetRange。
但是,如果我的TargetRange工作簿上的列c2中存在数据,我需要将SourceRange放入TargetRange中的下一个可用列。
如果c2中没有数据,如果c2中没有数据,则下面的代码将以黄色复制SourceRange,绿色实例需要在c2之后粘贴到下一个可用列中,所以d2。
我知道偏移功能,但我不确定应该在哪里使用它。
Select Case MasterWorkbook.ActiveSheet.Range("c2") = ""
Case True
' The opened file automatically becomes the new active workbook and active worksheet.
Set SourceRange = ActiveSheet.Range("c2:c26")
Set TargetRange = MasterWorkbook.ActiveSheet.Range("c2:c29")
' Copy cell values one at a time from the source range to the target range.
For Row = 2 To 29
TargetRange.Cells(Row, 1).Value = SourceRange.Cells(Row, 1).Value
Next
ActiveWorkbook.Close
' Set background colour of target range.
TargetRange.Select
With Selection.Interior
.ColorIndex = 6
.Pattern = xlSolid
End With
Case False
' The opened file automatically becomes the new active workbook and active worksheet.
Set SourceRange = ActiveSheet.Range("c2:c26")
Set TargetRange = MasterWorkbook.ActiveSheet.Range("c2:c29")
' Copy cell values one at a time from the source range to the target range.
'Sheets.Add.Name = "workbookname"
For Row = 2 To 29
TargetRange.Cells(Row, 1).Value = SourceRange.Cells(Row, 1).Value
Next
ActiveWorkbook.Close
' Set background colour of target range.
TargetRange.Select
With Selection.Interior
.ColorIndex = 10
.Pattern = xlSolid
End With
End Select
答案 0 :(得分:0)
试试这个
Sub test()
Dim SourceRange As Range
Dim TargetRange As Range
' The opened file automatically becomes the new active workbook and active worksheet.
Set SourceRange = ActiveSheet.Range("c2:c26")
Set TargetRange = MasterWorkbook.ActiveSheet.Range("b3")
If TargetRange.Text <> "" then
Set TargetRange = TargetRange.End(xlToRight).Offset(0, 1)
End If
Set TargetRange = MasterWorkbook.ActiveSheet.Range(TargetRange, TargetRange.Offset(25, 0))
' Copy cell values ALL AT ONCE from the source range to the target range.
SourceRange.Copy
TargetRange.PasteSpecial xlPasteValues
ActiveWorkbook.Close
' Set background colour of target range.
With TargetRange.Interior
.ColorIndex = IIf(TargetRange.Column = 3, 6, 10)
.Pattern = xlSolid
End With
End Sub
我建议你逐行逐步完成,这样你才能理解发生了什么。