0

我试图将指定的愤怒从一个工作簿粘贴到另一个工作簿,我指定的范围称为 SourceRange,其目的地是 TargetRange。

但是,如果我的 TargetRange 工作簿的 c2 列中存在数据,我需要将 SourceRange 粘贴到我的 TargetRange 中的下一个可用列中。

如果 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
4

1 回答 1

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

我建议您逐行浏览它,以便您了解正在发生的事情。

于 2012-12-05T23:18:07.837 回答