列号 - 从一个文件复制并粘贴到另一个文件

Column number - copying and pasting from file to another file

我的代码有点问题。我想将我的数据从一个文件复制到我的主文件。当我检查代码时遇到一个问题。该代码在复制之前工作正常。在这一行

Set cell1 = wsDest.Cells(1, Range("B1").End(xlToRight).Column + 1)

单元格是从我正在获取数据的文件中选择的,而不是我要粘贴到的文件夹。

我希望我的数据从这些其他文件粘贴到主文件中。我想将它们添加为列,而不是行。


Sub MoveCopyRowsColumns()

Dim mainWb As Workbook
Dim newWb As Workbook
Dim mainWs As Worksheet
Dim newWs As Worksheet
Dim strFolder As String

Set mainWb = Workbooks("Main_file.xlsm")
Set mainWs = mainWb.Worksheets("Worksheet1")

mainWs.Cells(1, Range("B1").End(xlToRight).Column + 1).Select
mainWs.Columns(ActiveCell.Column).EntireColumn.Delete

    strFolder = "C:\Users\User1\Desktop\Folder_with_files\"
    strFile = Dir(strFolder & "*.xls*")
    Do While strFile <> ""
        Set newWb = Workbooks.Open(strFolder & strFile)
        Set newWs = newWb.Sheets(1)
        
        strFile = Dir
        
        newWs.Cells(1, Range("B1").End(xlToRight).Column + 1).Select
        newWs.Columns(ActiveCell.Column).EntireColumn.Delete
        
        newWs.Range("B1", Range("B1").End(xlDown).End(xlToRight)).Copy _
        mainWs.Range("P1")
        
    Loop

End Sub

你必须声明哪个 file/sheet 是哪个。每行应引用正确的工作表。所有以单元格或范围开头的行都应该首先有工作表,例如:“mainWs.Cell”。 在新文件中,您没有声明任何工作表,只有工作簿 (wb)。 我还没有尝试过下面的代码,但我希望它能解开你的问题思维。 祝你好运!

Sub MoveCopyRowsColumns()
Dim mainWb As Workbook
Dim newWb As Workbook
Dim mainWs As Worksheet
Dim newWs As Worksheet
Dim strFolder As String
Dim strFile As String
Dim cell1 As Range

Set mainWb = Workbooks("Main_file.xlsm")
Set mainWs = mainWb.Worksheets("Worksheet1")

mainWs.Cells(1, Range("B1").End(xlToRight).Column + 1).Select   
mainWs.Columns(ActiveCell.Column).EntireColumn.Delete
'in my main file I delete the last column  only one

    strFolder = "C:\Users\User1\Desktop\Folder_with_files\"
    strFile = Dir(strFolder & "*.xls*")
    Do While strFile <> ""
        Set newWb = Workbooks.Open(strFolder & strFile)
        'Set the sheet you want to use, using "first sheet" or sheet by name
        'Set newWs = newWb.Sheets(1)
        'Set newWs = newWb.Worksheets("Worksheet1")
        strFile = Dir
        
        newWs.Cells(1, Range("B1").End(xlToRight).Column + 1).Select
        newWs.Columns(ActiveCell.Column).EntireColumn.Delete
        
        'Set cell1 = newWs.Cells(1, Range("B1").End(xlToRight).Column + 1)
        newWs.Cells(1, Range("B1").End(xlToRight).Column + 1).Copy  
        'the adress is taking from file when I take the data, not the main file which should take.
        
        mainWs.Range(cell1).PasteSpecial Paste:=xlPasteValues
    Loop

End Sub