vb.net 即使在设置变量后也出现延迟绑定问题

vb.net late bindings issue even after setting the variable

嘿,我有以下代码正在抛出 后期绑定

我想放:

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))

我收到以下错误:

Additional information: Unable to cast COM object of type 'System.__ComObject' to interface type 'Microsoft.Office.Interop.Excel.Worksheets'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{000208B1-0000-0000-C000-000000000046}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)).

请注意,您必须参考 Microsoft.Office.Interop.Excel 程序集: 项目>>添加引用>>检查Microsoft Excel x.xx Object Libary

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),因为您正在用 new 初始化它们工作簿和新工作表。

  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