如何将工作表从一个工作簿复制到另一个工作簿

时间:2019-08-30 16:09:21

标签: excel vba

我想从一个正在通过FilePath打开的工作簿中复制一张工作表到另一个包含正在运行的宏的工作簿中。

我遇到的麻烦是,每当我复制并粘贴文件时,宏就会创建一个新的工作簿并将数据粘贴到该工作簿的第一张工作表中。我在第二个工作簿中定义了一个特定的工作表来粘贴代码,所以我不确定为什么粘贴的目标是一个随机工作簿。

Invoke-RESTMethod -uri https://circleci.com/api/v1.1/project/$vcs_type/$username/$project/$build_number/artifacts?circle-token=$CIRCLE_TOKEN -Method GET

**Output:**

    ({
    :path “src/file1.txt”,
    :pretty-path “src/file1.txt”,
    :node-index 0,
    :url “https://15-198716507-gh.circle-artifacts.com/0/src/file1.txt”
    } {
    :path “src/file2.txt”,
    :pretty-path “src/file2.txt”,
    :node-index 0,
    :url “https://15-198716507-gh.circle-artifacts.com/0/src/file2.txt”
    }…continued

预期结果是复制粘贴将通过我的FileDialog从选择的工作簿复制到名为“ SPO DATA”的工作表中,我将其设置为变量 Public filepath As String Sub FileOpenDialogBox() 'Display a Dialog Box that allows to select a single file. 'The path for the file picked will be stored in fullpath variable With Application.FileDialog(msoFileDialogFilePicker) 'Makes sure the user can select only one file .AllowMultiSelect = False 'Filter to just the following types of files to narrow down selection options .Filters.Add "Excel Files", "*.xlsx; *.xlsm; *.xls; *.xlsb", 1 'Show the dialog box .Show 'Store in fullpath variable fullPath = .SelectedItems.Item(1) End With filepath = fullPath 'It's a good idea to still check if the file type selected is accurate. 'Quit the procedure if the user didn't select the type of file we need. If InStr(fullPath, ".xls") = 0 Then Exit Sub End If 'Open the file selected by the user 'Workbooks.Open fullpath End Sub Sub CopySheet() 'Module 1 FilePath import as Variable MsgBox filepath Dim spo_book As Workbook Dim target_book As Workbook Set spo_book = ActiveWorkbook Set target_book = Workbooks.Open(filepath) Dim dst_sheet As Worksheet Dim target_sheet As Worksheet Set dst_sheet = spo_book.Sheets("SPO Data") Set target_sheet = target_book.Sheets("Untimed Parts") target_sheet.Copy dst_sheet.Paste End Sub ,我认为这可能是一个范围问题,我试图放入一个范围,它说数据不匹配,所以我返回到我的工作表粘贴。

1 个答案:

答案 0 :(得分:1)

有点老派了吗?

    sub sample()

    Application.ScreenUpdating = false
    Sheet1="Willy"
    Sheet2="Wilma"

    for row1=20 to 500
    for col= 30 to 3300

    Sheets(Sheet1).Cells(row1, col1).Value=Sheets(Sheet2).Cells(row2, col2).Value
    Sheets(Sheet1).Cells(row1, col1).Formula=Sheets(Sheet2).Cells(row2, col2).Formula
    Sheets(Sheet1).Cells(row1, col1).Comment=Sheets(Sheet2).Cells(row2, col2).Comment

    next
    next
    Application.ScreenUpdating = True
    end sub

'因为有人问过如何解决一些问题:)

  Sub ws_all()
  Dim wb As Workbook

For Each wb In Application.Workbooks
    Debug.Print wb.Name

    For Each ws In wb.Sheets

        Debug.Print ws.Name

    Next
Next

Debug.Print Application.Workbooks; ("Workbookname").Sheets  ("Sheetname").Name

End Sub