复制数据并粘贴为值

时间:2019-03-08 07:09:25

标签: excel vba copy-paste

我的代码当前将数据行从源工作簿复制到Mastercopy excel。但是,我想将值粘贴为数字。关于如何在下面的代码中进行修改的任何想法?

Sub copyDataFromMultipleWorkbooksIntoMaster()

Dim FolderPath As String, Filepath As String, Filename As String

FolderPath = "D:\Users\AlexPeteson\Desktop\Test File\Downloads\"

Filepath = FolderPath & "*.csv"

Filename = Dir(Filepath)

Dim lastrow As Long, lastcolumn As Long

Dim erow

Do While Filename <> ""
Workbooks.Open (FolderPath & Filename)

'Find the last non-blank cell in column A(1)
lastrow = ActiveSheet.Cells(Rows.Count, 1).End(xlUp).Row

'Find the last non-blank cell in row 1
lastcolumn = ActiveSheet.Cells(3, Columns.Count).End(xlToLeft).Column

Range(Cells(3, 1), Cells(lastrow, lastcolumn)).copy
Application.DisplayAlerts = False
ActiveWorkbook.Close

erow = Sheet1.Cells(Rows.Count, 2).End(xlUp).Offset(1, 0).Row

ActiveSheet.Paste Destination:=Worksheets("Sheet1").Range(Cells(erow, 2), Cells(erow, 10))

Filename = Dir

Loop

End Sub

1 个答案:

答案 0 :(得分:0)

您可以在Set ws = ...上编辑主表名称

Option Explicit
Sub copyDataFromMultipleWorkbooksIntoMaster()

    Dim FolderPath As String, Filepath As String, Filename As String
    Dim wb As Workbook, ws As Worksheet, wbTemp As Workbook, wsTemp As Worksheet

    'Define your master workbook and sheet
    Set wb = ThisWorkbook
    Set ws = wb.Sheets("YourMasterSheetName")

    FolderPath = "D:\Users\AlexPeteson\Desktop\Test File\Downloads\"

    Filepath = FolderPath & "*.csv"

    Filename = Dir(Filepath)

    Dim lastrow As Long, lastcolumn As Long

    Dim erow As Long

    Do While Filename <> ""
        Set wbTemp = Workbooks.Open(FolderPath & Filename, UpdateLinks:=False, ReadOnly:=True)
        Set wsTemp = wbTemp.Sheets(1) ' lets suppose it is always on the first sheet in the workbook

        With wsTemp
            'Find the last non-blank cell in column A(1)
            lastrow = .Cells(Rows.Count, 1).End(xlUp).Row
            'Find the last non-blank cell in row 1
            lastcolumn = .Cells(3, Columns.Count).End(xlToLeft).Column
            .Range(Cells(3, 1), Cells(lastrow, lastcolumn)).Copy
        End With
        'Find the last blank cell on your master sheet
        erow = ws.Cells(Rows.Count, 2).End(xlUp).Row + 1
        ws.Cells(erow, 2).PasteSpecial xlPasteValues
        wbTemp.Close Savechanges:=False
        Set wbTemp = Nothing
        Set wsTemp = Nothing
        Filename = Dir
    Loop

End Sub
相关问题