VB写入Excel

我试图写在VB中的Excel文件,但由于嵌套循环结构(我认为),我遇到了麻烦。 我的代码如下:

Public Class Form1 Dim SheetIncrementValue As Integer = 1 Dim FilePath As String Dim j As Integer = 0 Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click Dim TestOutput() As Double If j = 0 Then If SheetIncrementValue = 1 Then wb = xl.Workbooks.Add 'create new workbook ws = wb.Worksheets(SheetIncrementValue) ws.Activate() ws.Cells(j + 1, 1) = TestOutput(j) Dim sfd1 As New SaveFileDialog() SetPath If sfd1.ShowDialog() = DialogResult.OK Then wb.SaveAs(sfd1.FileName) 'save data to file ws.Name = "Temperature " & TempSetting FilePath = sfd1.FileName wb.Close() xl = Nothing 'dispose of excel Else MsgBox("please choose a file path and file name") GoTo SetPath End If Else wb = xl.Workbooks.Open(FilePath) Dim worksheets As Excel.Sheets = wb.Worksheets Dim xlNewSheet = DirectCast(worksheets.Add(worksheets(1), Type.Missing, Type.Missing, Type.Missing), Excel.Worksheet) xlNewSheet.Name = "Output " & SheetIncrementValue xlNewSheet.Cells(j + 1, 1) = TestOutput(j) wb.Close() xl = Nothing 'dispose of excel End If Else wb = xl.Workbooks.Open(FilePath) Dim worksheets As Excel.Sheets = wb.Worksheets 'Dim xlNewSheet = DirectCast(worksheets.Add(worksheets(1), Type.Missing, Type.Missing, Type.Missing), Excel.Worksheet) Dim xlNewSheet = wb.Worksheets("Output " & SheetIncrementValue) xlNewSheet.Cells(j + 1, 1) = TestOutput(j) wb.Close() xl = Nothing 'dispose of excel End If j = j + 1 SheetIncrementValue = SheetIncrementValue + 1 End Sub End Class 

当j = 0时它工作正常,但是对于更高的增量,它会抛出错误:“对象引用未设置为对象的实例”。 在FilePath行。 由于该文件已经存在,并且已经分配了variablesFilePath(我选中了),那么如何再次打开该文件以将更多的数据写入同一个工作表?

我意识到使用'j'和'表单增量值'在这里是多余的,但是它们在我的完整代码中有function。

任何提示赞赏。

谢谢

无需编写如此多的代码行,只需使用GemBox SpreadSheet