此代码出现编译错误,我试图以SourceFileName
为目标,而无需打开并将其加载到我的活动工作簿工作表“数据检索”中
我得到compile error, sub of function not defined
。
Sub test()
Set appxl = CreateObject("Excel.application")
Dim myfile As Window
Dim currentSheet As Worksheet
Dim lastRow As Double
Dim sourceFileName As String
sourceFileName = "File name"
'Open Source File.xlsx
With appxl
.Workbooks.Open ActiveWorkbook.Path & "\" & sourceFileName
.Visible = False
End With
'Get first sheet data
Set myfile = appxl.Windows(sourceFileName)
myfile.Activate
Set currentSheet = appxl.Sheets(12)
'Past the table in my current Excel file
lastRow = currentSheet.Range("A1").End(xlDown).Row
Sheets("Data retrieval").Range("A1:E" & lastRow) = currentSheet.Range("A1:E" & lastRow).Value
'Close Source File.xlsx
appxl.Workbooks(sourceFileName).Close
End Sub
应用以下Option Explicit
的建议并声明appxl
后,出现以下错误:
答案 0 :(得分:2)
我推荐以下内容
Option Explicit
Sub test()
Dim AppXl As Excel.Application
Set AppXl = New Excel.Application
AppXl.Visible = False
Dim sourceFileName As String
sourceFileName = "File name"
'Open Source File.xlsx
Dim SourceWb As Workbook 'remember workbook in a variable so we can easily access it
Set SourceWb = AppXl.Workbooks.Open(ThisWorkbook.Path & "\" & sourceFileName)
'Get first sheet data
Dim currentSheet As Worksheet
Set currentSheet = SourceWb.Sheets(12)
'Past the table in my current Excel file
Dim lastRow As Long 'row counting variables MUST be Long
lastRow = currentSheet.Range("A1").End(xlDown).Row
'define the workbook here
ThisWorkbook.Worksheets("Data retrieval").Range("A1:E" & lastRow).Value = currentSheet.Range("A1:E" & lastRow).Value
'Close Source File.xlsx
SourceWb.Close SaveChanges:=False 'close source without saving
AppXl.Quit
End Sub