从VISUAL BASIC FORM插入EXCEL作为DB

时间:2018-01-05 12:14:27

标签: excel vb.net visual-studio

我想将来自visual basic的userform的文本框数据放到excel(Sheet1)作为Database。我正在使用Excel 2016,工具是Visual Studio 2013专业版。我创建了这样的形式:

enter image description here,代码为:

       Imports System.Data.OleDb
       Imports System.IO
       Public Class Form2

   Dim cn As OleDbConnection
   Dim cm As OleDbCommand


Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Const path As String = "C:\\Users\\echat\\Desktop\\Book2.xls"
    ' Const connstring As String = "Provider==Microsoft.ACE.OLEDB.12.0;Data Source=" + path + ";Extended Properties=Excel 12.0;HDR=YES;"""
    ' cn.ConnectionString = "provider=microsoft.jet.oledb.4.0;data source=C:\Connect To Excel\Book2.xls;extended properties=excel 5.0;"
    cn.ConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;data source=C:\Connect To Excel\Book2.xls;Extended Properties=""Excel 12.0 Xml;HDR=YES"";"

    cn.Open()

    With cm
        .Connection = cn
        .CommandText = "Insert into [Sheet1]values ('" & TextBox1.Text & "','" & TextBox2.Text & "') "
        .ExecuteNonQuery()

    End With

    cn.Close()
    MsgBox("Success", MsgBoxStyle.Information, Text)

End Sub
End Class

我已尝试但在这一行中给出错误:任何人都可以纠正它吗?

  

System.NullReferenceException:未将对象引用设置为实例   一个对象。

enter image description here

1 个答案:

答案 0 :(得分:2)

您尚未初始化连接对象。

试试这个:

   Dim cn As new OleDbConnection
   Dim cm As new OleDbCommand