VBA将交替的列复制到相邻列

时间:2018-06-28 04:50:26

标签: excel vba excel-vba csv

所以我想将DC和DE列从一个文件复制到N和O列从另一个文件。现在,有了代码,我就从N列和O列的DC列中复制了值。我检查并用Range("DC2:DC" & numRows & "," & "DE2:DE" & numRows)选择了正确的列。

Set wbCSV = Workbooks.Open(Filename:=Worksheets("Sheet1").TextBox1.Value)

'Copy data
With wbCSV
 numRows = Cells(Rows.Count, "A").End(xlUp).Row
 LTOE = .Sheets(1).Range("DC2:DC" & numRows & "," & "DE2:DE" & numRows).Value
 .Close
End With

'Paste data
Worksheets("Sheet1").Range("N18:O" & numRows + 16).Value = LTOE

1 个答案:

答案 0 :(得分:1)

不连续列的并集不适用于直接值传递或数组。采取额外的步骤将数据拖到一列上。

dim LTOE  as variant, i as long

Set wbCSV = Workbooks.Open(Filename:=Worksheets("Sheet1").TextBox1.Value)

'Copy data
With wbCSV
    numRows = .Cells(.Rows.Count, "A").End(xlUp).Row
    LTOE = .Sheets(1).Range("DC2:DE" & numRows).Value
    .Close
End With

'tighten the columns up
for i=lbound(LTOE , 1) to ubound(LTOE ,1)
    LTOE(i, 2) = LTOE(i, 3)
next i

'remove the extra column (ok with preserve since we are resizing the last rank)
redim preserve LTOE(lbound(LTOE , 1) to ubound(LTOE ,1), 1 to 2)

'Paste data
Worksheets("Sheet1").Range("N18).resize(ubound(ltoe, 1), ubound(ltoe, 2)) = LTOE
相关问题