创建一个复制和粘贴数据的宏

Create a macro that copy and pastes data

我正在尝试创建一个宏来打开一个文件,然后将该文件中的数据复制并粘贴到一个新的 excel sheet 中。

问题是,该文件每月更新一次。因此,我在 excel 上有一个 sheet,我已将路径复制粘贴到该文件(说明及其在单元格 A2 中)。我想知道如何调整我的代码以打开该文件、复制其数据并关闭该文件。我还想创建一个按钮,我可以按下它来 运行 宏。

到目前为止,这是我的代码:

Sub ImportData_Click()
'open the source workbook and select the source sheet
Workbooks.Open Filename:="'Instructions!'$A"   'this is the part of the 
code that I'm having trouble with
Sheets("ABC").Select

' copy the source range
Sheets("ABC").Range("C:AI").Select
Selection.Copy

' select current workbook and paste the values 
ThisWorkbook.Activate
Sheets("ABC DUMP").Select
Sheets("ABC DUMP").Range("A:").Select
Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:= _
False, Transpose:=False

'close the source workbook
Windows("'Instructions!'$A").Activate    

ActiveWorkbook.Close

End Sub

如果您将变量定义为字符串,然后将其设置为等于您的文件名 ('Instructions!'$A$2),则您可以在 workbooks.open 函数中使用此变量。

您的 workbooks.open 函数还需要此工作簿的路径名;因此,为您的路径名定义另一个变量,您应该能够使用:

Workbooks.Open 文件名:=路径名和文件名

您有几个小的语法错误。 A2 数据如:

C:\TestFolder\ABC.xls

这似乎工作得很好:

Sub ImportData_Click()
    'open the source workbook and select the source
    Dim wb As Workbook

    Workbooks.Open Filename:=Sheets("Instructions").Range("$A").Value
    Set wb = ActiveWorkbook
    Sheets("ABC").Select

    ' copy the source range
    Sheets("ABC").Range("C:AI").Select
    Selection.Copy

    ' select current workbook and paste the values
    ThisWorkbook.Activate
    Sheets("ABC DUMP").Select
    Sheets("ABC DUMP").Range("A1").Select
    Selection.PasteSpecial Paste:=xlValues, Operation:=xlNone, SkipBlanks:= _
        False, Transpose:=False

    'close the source workbook

    wb.Close

End Sub

这个可以重新编码避免Select