运行此代码时,我在activeworkbook.sheets.add
命令
还尝试objexcel.sheets.add("Test")
并收到“Sheets类的添加方法失败”。
Public Sub InitialConditions(FileName As Variant)
Dim objexcel As Object
Dim wbexcel As Object
Set objexcel = CreateObject("excel.Application")
Set wbexcel = objexcel.workbooks.Open(FileName)
activeworkbook.sheets.Add ("Test")
objexcel.Visible = True
End Sub
答案 0 :(得分:2)
您的代码使用后期绑定。但Excel对象模型丰富而复杂。所以我认为在开发和测试期间使用早期绑定会更好。这样你就可以利用Intellisense来指导你,编译器将能够更彻底地发现问题。
Public Sub InitialConditions(FileName As String)
'* enable these 4 lines for deployment
' Dim objexcel As Object
' Dim wbexcel As Object
' Dim objsheet As Object
' Set objexcel = CreateObject("excel.Application")
'* enable these 4 lines for development and testing
'* (requires reference to Excel Object Library)
Dim objexcel As Excel.Application
Dim wbexcel As Excel.Workbook
Dim objsheet As Excel.Worksheet
Set objexcel = New Excel.Workbook
Set wbexcel = objexcel.Workbooks.Open(FileName)
' ActiveWorkbook.Sheets.Add ("Test")
Set objsheet = wbexcel.Sheets.Add
objsheet.Name = "Test"
objexcel.Visible = True
End Sub
当您准备部署应用程序时,可以切换回后期绑定。这允许您删除Excel引用,这减少了生产使用中引用问题的可能性。
答案 1 :(得分:-1)
尝试
activeworkbook.sheets.add after:=activeworkbook.sheets(activeworkbook.sheets.count)
activeworkbook.sheets(activeworkbook.sheets.count).Name = "Test"