![](/img/trans.png)
[英]How can I copy non-contiguous cells from a workbook to a different set of non-contiguous cells in another workbook?
[英]Copy data from non-contiguous cells
Option Explicit
Sub CopyNonContiguous()
' Constants
' Source
Const sName As String = "Sheet1"
Const sAddress As String = "G3:G6,G8:G15"
' Destination
Const dName As String = "Sheet1"
Const dAddress As String = "B3:B4,B6:B7,B9:E10"
' Workbook
Dim wb As Workbook: Set wb = ThisWorkbook ' workbook containing this code
' Destination Range
Dim dws As Worksheet: Set dws = wb.Worksheets(dName)
Dim drg As Range: Set drg = dws.Range(dAddress)
'drg.Interior.Color = 14348258 ' green
' Source Range
Dim sws As Worksheet: Set sws = wb.Worksheets(sName)
Dim srg As Range: Set srg = sws.Range(sAddress)
'srg.Interior.Color = 13431551 ' yellow
' Source Data Array
Dim scCount As Long: scCount = srg.Cells.Count
Dim sData As Variant: ReDim sData(1 To scCount)
' Additional Variables
Dim arg As Range ' Current Range Area
Dim cel As Range ' Current Cell in Current Range Area
Dim n As Long ' Source Data Array Elements Counter
' Source Range to Source Data Array
For Each arg In srg.Areas
For Each cel In arg.Cells
n = n + 1
'cel.Value = n ' to populate the Source Range
sData(n) = cel.Value
Next cel
Next arg
' Source Data Array to Destination Range
' Reset 'n' because at this moment 'n = scCount'.
n = 0
For Each arg In drg.Areas
For Each cel In arg.Cells
n = n + 1
cel.Value = sData(n)
' Since the Destination Range could contain more cells than
' the Source Range, test with the following:
If n = scCount Then Exit Sub
Next cel
Next arg
End Sub
您可以“記錄宏”,然后將您想要的所有字段復制到正確的位置?
記錄的代碼如下所示:
Sub Macro1()
'
' Macro1 Macro
'
'
Range("G3:G4").Select
Selection.Copy
Range("B3").Select
ActiveSheet.Paste
Range("G5:G6").Select
Application.CutCopyMode = False
Selection.Copy
Range("B6").Select
ActiveSheet.Paste
Range("G8:G11").Select
Application.CutCopyMode = False
Selection.Copy
Range("B9").Select
Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:= _
False, Transpose:=True
Range("G12:G15").Select
Application.CutCopyMode = False
Selection.Copy
Range("B10").Select
Selection.PasteSpecial Paste:=xlPasteAll, Operation:=xlNone, SkipBlanks:= _
False, Transpose:=True
Range("B12").Select
End Sub
編輯:沒有Select
它可能看起來像這樣:
Sub macro2()
Dim a As Worksheet
Set a = ActiveSheet
a.Range("G3:G4").Copy Destination:=a.Range("B3")
a.Range("G5:G6").Copy Destination:=a.Range("B6")
a.Range("B9:E9") = Application.WorksheetFunction.Transpose(a.Range("G8:G111"))
a.Range("B10:E10") = Application.WorksheetFunction.Transpose(a.Range("G12:G15"))
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.