将行从一个 excel 文件复制到另一个文件并在右列中分配 row.cells

Copy rows from one excel file to another and allocate row.cells in the right columns

我一直在尝试将一系列行(每行 4 列)复制到一个新的 csv 文件中。我希望正确分配单元格。这些文件如下所示。

因此,需要将"Code"、"Name"、"Surname"、"Number"个单元格复制并粘贴到新文件的右侧单元格中。

因此,例如,FileA 的第二行将粘贴到 FileB 中,如下所示:

UPD: 我正在使用此代码 select 行的范围并将它们粘贴到新文件中。

Sub ExportRangetoFile()
Dim Rng As Range
Dim WorkRng As Range
Dim lRow As Long, lCol As Long
Dim xFile As Variant
Dim xFileString As String
On Error Resume Next

    lRow = Range("A" & Rows.Count).End(xlUp).row
    lCol = Cells(1, Columns.Count).End(xlToLeft).Column
    Set Rng = Range(Cells(lRow, 1), Cells(lRow, lCol))


ActiveSheet.Copy
ActiveSheet.Cells.Clear
Rng.Copy Application.ActiveSheet.Range(Cells(lRow, 1), Cells(lRow, lCol))

Columns("C:C").Cut: Columns("B:B").Insert Shift:=xlToRight
Set xFile = CreateObject("Scripting.FileSystemObject")
ActiveWorkbook.SaveAs Filename:="C:\Users\User\Desktop\Range.csv", FileFormat:=xlCSV, CreateBackup:=False
End Sub

我想更改代码以便在新文件中创建 headers 并在右列中分配每行的单元格。

UPD: 我的问题是我的代码需要更改。在新文件中,我只得到一行而不是全部。作为第一步,必须在此处进行更改:

ActiveSheet.Copy
ActiveSheet.Cells.Clear
Rng.Copy Application.ActiveSheet.Range(Cells(lRow, 1), Cells(lRow, lCol))

然后我需要搜索如何在新的 csv 文件中创建 headers。

我试着稍微修改一下您的代码,最后得到了这个宏,我认为它可以满足您的需求,同时大大简化了您发布的代码片段。如果我在某些方面误解了您的要求,或者有什么需要进一步解释的地方,请随时提出。

Option Explicit

Sub ExportRangetoFile()
  Dim cpFromRng As Range, cpToRng As Range
  Dim cpFromWB As Workbook, cpToWB As Workbook
  Dim lRow As Long, lCol As Long

  Set cpFromWB = ActiveWorkbook
  ' Set range to copy
  With cpFromWB
    lRow = Range("A" & Rows.Count).End(xlUp).Row
    lCol = Cells(1, Columns.Count).End(xlToLeft).Column
    ' I assume the top left cell you want to copy from is A1, if that is wrong, change the line below back
    Set cpFromRng = Range(Cells(1, 1), Cells(lRow, lCol))
  End With
  ' Create new workbook
  Set cpToWB = Workbooks.Add
  Set cpToRng = cpToWB.ActiveSheet.Range("A1")

  ' Copy everything over to the new workbook
  cpFromRng.Copy Destination:=cpToRng

  ' Shuffle columns around
  cpToWB.ActiveSheet.Columns("C:C").Cut
  cpToWB.ActiveSheet.Columns("B:B").Insert Shift:=xlToRight

  ' Save as CSV-file
  ActiveWorkbook.SaveAs Filename:="C:\Users\a245401\Range.csv", FileFormat:=xlCSV, CreateBackup:=False
End Sub