MS EXCEL VBA – 我需要从一个Excel文件导入到另一个工作表

我需要从一个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 

此代码将为你想要的东西工作。 我做了以下更正。

  1. 将所有variables的声明移到程序开始处,以便在使用它们之前声明它们。 这只是一个好习惯。

  2. 在打开第二个工作簿之前,将您的活动工作簿分配给该variables,以便只打开一个工作簿。

  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 

将工作簿设置为打开(或稍后在不使用文件path的情况下设置工作簿)

干得好:

 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