我正在从Excel VBA过渡到VB.NET,所以如果这是一个愚蠢的问题,请放轻松我。我在以下子行的这一行得到NullReferenceException was unhandled by user code
:
Dim objSheet As Excel.Worksheet = objBook.Sheets("SQL Creator")
VS说Object reference is not set to an instance of the object
。我不确定为什么要这样做,因为我已经在objApp变量中声明了一个新的Excel实例。为什么我需要在该类下声明每个对象的新实例?我很可能没有正确地思考这个问题,但我只是想提一下我的想法。总的来说,我只是试图测试下面的子项,看看它是否会打开和关闭与PostgreSQL数据库的连接。
导入Microsoft.Office.Interop
Public Sub QueryData(ByVal ribbonUI As Office.IRibbonControl)
Dim objApp As New Excel.Application
Dim objBook As Excel.Workbook = objApp.ActiveWorkbook
Dim objSheet As Excel.Worksheet = objBook.Sheets("SQL Creator")
Dim pgconn As String
pgconn = "Driver={PostgreSQL};" &
"Server = localhost;" &
"Port = 5432;" &
"Database = CFABudget;" &
"Uid = postgres;" &
"Pwd = budgeto;"
Dim SQL As String = objSheet.Range("BudgetSQL").Text
Dim conn As New Data.Odbc.OdbcConnection(pgconn)
Dim cmd As Data.Odbc.OdbcCommand = New Data.Odbc.OdbcCommand(SQL)
conn.Open()
MsgBox("Success!", vbOKOnly)
conn.Close()
End Sub
谢谢大家的帮助!
答案 0 :(得分:0)
替换
Dim objApp As New Excel.Application
使用:
Dim objApp As Excel.Application = System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application")
您试图从新的空Excel实例中获取活动工作簿。