我想:
Dim excelWS As Worksheet
excelWS = New Worksheet
在使用变量修正后期绑定问题之前?
更新1
会是这样的吗?
Dim excelRange As Range
Dim excelApp As Application
Dim excelWB As Workbook
Dim excelWS As Worksheets
excelWB = New Workbook
If madeSheet = False Then
excelApp = New Application
excelWB = excelApp.Workbooks.Add
excelApp.Visible = True
End If
excelWS = New Worksheet
更新2
现在就在这一行:
excelWS = excelWB.Worksheets.Add(After:=excelWB.Worksheets(sheetLoops))
我收到错误:
附加信息:无法转换类型为' System .__ ComObject'的COM对象。接口类型' Microsoft.Office.Interop.Excel.Worksheets'。此操作失败,因为QueryInterface调用COM组件上的接口与IID' {000208B1-0000-0000-C000-000000000046}'由于以下错误而失败:不支持此类接口(HRESULT异常:0x80004002(E_NOINTERFACE))。
答案 0 :(得分:0)
请注意,您必须重新Microsoft.Office.Interop.Excel
汇编:
project>> add reference>>检查Microsoft Excel x.xx对象库
Imports Microsoft.Office.Interop
Public Class Form1
Private exapp As Excel.Application
Private xlwb As Excel.Workbook
Private xlws As Excel.Worksheet
Private Sub Form1_Load(sender As Object, e As EventArgs) Handles MyBase.Load
exapp = New Excel.Application
xlwb = exapp.Workbooks.Add()
xlws = xlwb.Worksheets.Add()
xlws.Name = "MY WS"
xlws.Move(After:=xlwb.Sheets(xlwb.Sheets.Count))
' note: .value is a Range property
xlws.Cells(1, 2) = "standard"
xlwb.Application.DisplayAlerts = False
exapp.Visible = True
xlwb.Worksheets("sheet1").Delete()
xlwb.SaveAs("C:\Users\john\Desktop\test.xlsx")
xlwb.Close()
End Sub
End Class
至于您的更新:
即使Excel.Worksheet和Excel.Workbook也不是静态对象,在你的情况下你不需要立即使用(new
),因为你正在使用新工作簿和新工作表初始化它们。 / p>
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim excelRange As Excel.Range
Dim excelApp As Excel.Application
Dim excelWB As Excel.Workbook
Dim excelWS As Excel.Worksheets
' excelWB = New Workbook - you dont need an instant
' If madeSheet = False Then
excelApp = New Excel.Application
excelWB = excelApp.Workbooks.Add
excelApp.Visible = True
' End If
' excelWS = New Worksheet - you dont need an instant
End Sub