MS EXCEL VBA - 我需要将一个excel文件中的工作表导入到另一个excel文件中

时间:2012-03-20 16:05:10

标签: excel vba excel-vba spreadsheet

我需要从一个Excel工作簿导入工作表(工作表名称并不总是相同)并将其导入当前活动工作簿。

这是我到目前为止所做的:

Sub openFile_Click()
    FileToOpen = Application.GetOpenFilename _
    (Title:="Please choose a Report to Parse", _
    FileFilter:="Report Files *.rpt (*.rpt),")

    If FileToOpen = False Then
        MsgBox "No File Specified.", vbExclamation, "ERROR"
        Exit Sub
    Else
        Workbooks.Open Filename:=FileToOpen

        Dim wb1 As Workbook
        Dim wb2 As Workbook
        Set wb1 = ActiveWorkbook
        wb2 = Workbooks(FileToOpen)     'This is where I am stuck..I can't give it a static name

        For Each Sheet In wb1.Sheets
            If Sheets.Visible = True Then
                Sheets.Copy After:=wb2.Sheets(wb2.Sheets.Count)
            End If

        Next Sheet

    End If

2 个答案:

答案 0 :(得分:2)

此代码适用于您想要的内容。我做了以下更正。

  1. 将变量的所有声明移动到过程的开头,以便在使用它们之前声明它们。这只是一种很好的做法。

  2. 在打开第二个工作簿之前将Active Workbook分配给变量,这样只打开一个工作簿。

  3. 您的每个陈述也都有一些更正。

    Sub openFile_Click()
    Dim wb1 As Workbook
    Dim wb2 As Workbook
    
    Set wb1 = ActiveWorkbook
    
    FileToOpen = Application.GetOpenFilename _
    (Title:="Please choose a Report to Parse", _
    FileFilter:="Report Files *.rpt (*.rpt),")
    
    If FileToOpen = False Then
        MsgBox "No File Specified.", vbExclamation, "ERROR"
        Exit Sub
    Else
        Set wb2 = Workbooks.Open(Filename:=FileToOpen)
    
        For Each Sheet In wb2.Sheets
            If Sheet.Visible = True Then
                Sheet.Copy After:=wb1.Sheets(wb1.Sheets.Count)
            End If
        Next Sheet
    
    End If
    
    End Sub
    

答案 1 :(得分:0)

将工作簿设置为打开,(或稍后在没有文件路径的情况下设置工作簿)

你走了:

Sub openFile_Click()
FileToOpen = Application.GetOpenFilename _
(Title:="Please choose a Report to Parse", _
FileFilter:="Report Files *.rpt (*.rpt),")

If FileToOpen = False Then
    MsgBox "No File Specified.", vbExclamation, "ERROR"
    Exit Sub
Else
    Dim wb1 As Workbook
    Dim wb2 As Workbook
    Set wb1 = ActiveWorkbook
    Set wb2 = Workbooks.Open(FileToOpen)




    For Each Sheet In wb1.Sheets
        If Sheet.Visible = True Then
            Sheets.Copy After:=wb2.Sheets(wb2.Sheets.Count)
        End If

    Next Sheet

End If
End Sub