在VBA中导入工作表时出错

时间:2014-09-08 12:55:31

标签: excel vba excel-vba

我正在尝试编写VBA宏以从其他工作簿导入工作表。我得到一个"下标超出范围" " copy"上的错误线。文件打开正确,但我不确定之后会出现什么问题。

Private Sub CommandButton1_Click()

Application.ScreenUpdating = False
Application.DisplayAlerts = False

Dim lastdate As String, filename As String

lastdate = Format(sheet_1.Range("D11") - 7, "ddmmyy")
filename = "C:\Dir\file " & lastdate & ".xlsm"

Workbooks.Open (filename)
Workbooks(filename).Worksheets(2).Copy after:=ThisWorkbook.Worksheets(1)

Workbooks(filename).Close

Application.ScreenUpdating = True
Application.DisplayAlerts = False

End Sub

编辑:错误更改为"下标超出范围",代码已更改,因此索引引用了工作表。

代码v2:

Private Sub CommandButton1_Click()

Application.ScreenUpdating = False
Application.DisplayAlerts = False

Dim lastdate As String, filename As String

lastdate = Format(sheet1.Range("D11") - 7, "ddmmyy")
filename = "C:\Dir\file " & lastdate & ".xlsm"

Dim wbk As Workbook
wbk = Workbooks.Open(filename)

wbk.Worksheets(2).Copy after:=ThisWorkbook.Worksheets(1)
wbk.Close

End Sub

3 个答案:

答案 0 :(得分:3)

您的下标超出范围错误,因为您没有工作簿的Name权限。 Name与完整路径不同(这是你一直假设的);它与文件名相同。

这将有效:

Workbooks.Open "C:\Dir\file1234.xlsm"
Workbooks("file1234.xlsm").Sheets(1).Range("a1").Value = "yay"

虽然这赢了:

Workbooks.Open "C:\Dir\file1234.xlsm"
Workbooks("C:\Dir\file1234.xlsm").Sheets(1).Range("a1").Value = "yay"

但引用工作簿的更好方法是设置一个明确的引用,如下所示:

Dim wbk As Workbook
Set wbk = Workbooks.Open(filename)
wbk.Worksheets(2).Copy after:=ThisWorkbook.Worksheets(1)

使用wbk,您现在可以处理所需的工作簿;你不必猜出它的名字或任何东西。

答案 1 :(得分:1)

关键字'设置'在引用对象变量时需要:

Private Sub CommandButton1_Click()

Application.ScreenUpdating = False
'Application.DisplayAlerts = False '<<this does not look like it is required - when is an alert displayed in the method?

Dim lastdate As String, filename As String

lastdate = Format(sheet1.Range("D11") - 7, "ddmmyy")
filename = "C:\Dir\file " & lastdate & ".xlsm"

Dim wbk As Workbook
Set wbk = Workbooks.Open(filename)   '<<Set is required

wbk.Worksheets(2).Copy after:=ThisWorkbook.Worksheets(1)
wbk.Close

End Sub

答案 2 :(得分:-1)

Option Explicit

Sub Import_Worksheets()

Dim FolderPath As String
Dim Filename As String
Dim sheet As Worksheet

Application.ScreenUpdating = False
Application.DisplayAlerts = False

FolderPath = "H:G:\D S Class\Excel VBA (Macro)\RTO form\VBA\"
Filename = Dir(FolderPath & "RESTAURANT_USAGE_DATA.xlsx")

Do While Filename <> ""
 Workbooks.Open Filename:=FolderPath & Filename, ReadOnly:=True
 For Each sheet In ActiveWorkbook.Sheets
 sheet.Copy After:=ThisWorkbook.Sheets(1)
 Next sheet
 Workbooks(Filename).Close
 Filename = Dir()
Loop

Application.ScreenUpdating = True
Application.DisplayAlerts = True

End Sub

    enter code here