NullReferenceException was unhandled by user code - declaring Excel.Worksheet object - vb.net

I'm transitioning from Excel VBA to VB.NET, so if this is a dumb question, please go easy on me. I get a NullReferenceException was unhandled by user code on this line of the following sub:
Dim objSheet As Excel.Worksheet = objBook.Sheets("SQL Creator")
VS says that the Object reference is not set to an instance of the object. I'm not sure why it's asking for that, because I've already declared a new instance of Excel in the objApp variable. Why would I need to declare a new instance of each object under that class? It's very possible I'm not thinking about that correctly, but I just wanted to mention my thoughts. Overall, I'm just trying to test the sub below to see if it will open and close a connection to a PostgreSQL database.
Imports 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
Thank you all for your help!

Replace
Dim objApp As New Excel.Application
With:
Dim objApp As Excel.Application = System.Runtime.InteropServices.Marshal.GetActiveObject("Excel.Application")
You were trying to get active workbook from new empty instance of excel.

Related

Add Reference Library to an outside MS Access Database

I have a code that creates new MS Access Databases. I'd like to add reference libraries to these newly created MS Access Databases.
Here is the code that I wrote but is not working:
Sub makeDb(fl As String)
Dim fs
Set fs = CreateObject("Scripting.FileSystemObject")
'check if the file already exists
If fs.FileExists(fl) = False Then
'create new ms access database
Dim accessApp As Access.Application
Set accessApp = New Access.Application
accessApp.DBEngine.CreateDatabase fl, dbLangGeneral
'loop through all references in current database and add them to the newly created dbs
Dim cur_vbProj As VBIDE.VBProject: Set cur_vbProj = Application.VBE.VBProjects(1)
Dim cur_vbRefs As VBIDE.References: Set cur_vbRefs = cur_vbProj.References
Dim cur_vbRef As VBIDE.Reference
For Each cur_vbRef In cur_vbRefs
Dim cur_guid As String: cur_guid = cur_vbRef.Guid
Dim cur_major As Long: cur_major = cur_vbRef.Major
Dim cur_minor As Long: cur_minor = cur_vbRef.Minor
'here is the code that doesn't work
Dim vbProj As VBIDE.VBProject: Set vbProj = accessApp.Application.VBE.VBProjects(1)
Dim vbRefs As VBIDE.References: Set vbRefs = vbProj.References
vbRefs.AddFromGuid Guid:=cur_guid, Major:=cur_major, Minor:=cur_minor
Next
accessApp.Quit
Set accessApp = Nothing
End If
End Sub
The line Set vbProj = accessApp.Application.VBE.VBProjects(1) throws Run-Time error '9' Subscript out of range. How should I modify the code? Is it even possible to add references to an outside database?
Following works for me:
Sub makeDb(f1 As String)
Dim accApp As Access.Application
Dim cur_vbRefs As References
Dim cur_vbRef As Reference
If Dir(f1) = "" Then
Access.DBEngine.CreateDatabase f1, dbLangGeneral
Set accApp = New Access.Application
accApp.OpenCurrentDatabase f1
'loop through all references in current database and add them to the newly created dbs
Set cur_vbRefs = Application.References
For Each cur_vbRef In cur_vbRefs
On Error Resume Next
accApp.References.AddFromGuid cur_vbRef.Guid, cur_vbRef.Major, cur_vbRef.Minor
Next
End If
End Sub

How do I prevent .Run in Outlook from opening an Access instance twice?

In MS Outlook I have a button that calls a macro in MS Access. That macro opens a form and sets a text. Everytime if I push that button a new instance of Access is being opened. How do I prevent opening multiple instances of Access?
Outlook code:
'general declarations:
Public appAccess As Object
Sub OpenRecord()
Dim Reference As String
Dim docAccess
Reference = 'teststring'
Set appAccess = CreateObject("Access.Application")
docAccess = appAccess.opencurrentdatabase("D:\Database\MSA_db.accdb")
appAccess.Visible = True
appAccess.Run "OpenInternalReference", Reference
End Sub
Access Code:
Public Sub OpenInternalReference(MailReference As String)
Dim stDocName As String
Dim stLinkCriteria As String
stDocName = "browse"
DoCmd.OpenForm stDocName, , , stLinkCriteria
Forms("Browse").prefilter.SetFocus
Forms("Browse").prefilter.Text = MailReference
End Sub
Your problem is not the .Run method, it is your Set appAccess = CreateObject("Access.Application") since it always creates a new instance of access.
This code tries to get an Access Application that is already opened and creates a new if none is found:
Dim appAccess As Object
On Error Resume Next
Set appAccess = GetObject(Class:="Access.Application")
On Error GoTo 0
If appAccess Is Nothing Then
Set appAccess = CreateObject("Access.Application")
End If

Crystal report Formula Error String is required

I am working in crystal reports and I have created two parameters named startDate and endDate and when I go to Formula selection and I write the code and save it I got an error message "string is required"
the code is:
if {Employees.DateField} >={?startDatePF} and {Employees.DateField}<={?endDate} then true
Please tell me how can I resolve this error.
Public Sub GetReport()
Dim rpt As New CrystalReport1
rpt.Load(Application.StartupPath & "\CrystalReport1.rpt")
Dim pfield As New ParameterField
Dim pfields As New ParameterFields
Dim pdescrete As New ParameterDiscreteValue
Dim pfield1 As New ParameterField
Dim pfields1 As New ParameterFields
End Sub

Authenticating to Web Service VB.Net

Hi I am trying to Authenticate to my web service and missing something..
My Service reference is called - MBSDKServiceLD
My Web Reference is called - LANDeskMBSDK
I have these connected in Visual Studio 2013 And are resolving methods in the code
Here is my code for the authentication but its not complete..
Option Explicit On
Imports System.Net
Dim objFSO As Object
Dim objExec As Object
Dim objNetwork As Object
Dim strComputer As String
Dim strUser As String
Dim User As String
Dim Password As String
Dim Domain As String
Dim URL As String
Dim Cred As String
Dim strTaskName As String
Dim strPackageName As String
Dim strDeliveryMethod As String
Dim strCustomGroup As String
Dim boolStartNow As Boolean
Dim WakeUpMachines As Boolean
Dim boolCommonTask As Boolean
Dim strAutoSync As String
Dim TaskID As String
Dim strConnection As New System.Data.SqlClient.SqlConnection
Dim LDWebService
Dim intTaskID As String
Dim LDService As Object
Dim strDeviceName As String
Sub RunLANDeskTask(ByVal sender As Object, ByVal LDService As MBSDKServiceLD.MBSDKSoap)
End Sub
Sub CreateTask
User = "username1"
Password = "password1"
Domain = "domain1"
URL = "http://myserver/MBSDKService/MsgSDK.asmx?WSDL"
Dim MyCredentails As New System.Net.CredentialCache()
Dim NetCred As New System.Net.NetworkCredential(User, Password, Domain)
MyCredentails.Add(New Uri(URL), "Basic", NetCred)
strPackageName = "Adobe Acrobat XI PRO"
strDeliveryMethod = "Standard push distribution"
Dim strTargetDevice As String
strTargetDevice = Nothing
strTaskName = strPackageName & " - " & DateTime.Now & " -Provisioning Task for" & " " & strComputer
Try
RunLANDeskTask(LANDeskMBSDK, LDService.CreateTask(strTaskName, strDeliveryMethod, strPackageName, False, False, strAutoSync).TaskID)
Catch ex As Exception
MsgBox("Error creating task")
End Try
End Sub
What comes after this part or have i got this totally wrong?
When I type LDService. I see all the methods so I am connecting to the reference in VS but not authenticating.
It should really be as simple as this (sorry it's in c#):
MyWebService svc = new MyWebService();
svc.Credentials = new System.Net.NetworkCredential(UserID, pwd);
bool result = svc.MyWebMethod();
The following might be helpful:
This is quite old, but the comments are good.
I've just found the following on MSDN, which looks like what you want:
localhost.Sample svc = new localhost.Sample();
try {
CredentialCache credCache = new CredentialCache();
NetworkCredential netCred =
new NetworkCredential( "Example", "Test$123", "sseely2" );
credCache.Add( new Uri(svc.Url), "Basic", netCred );
svc.Credentials = credCache;
Ok i got this working... But i have to run the code under an account that can access the Web service -
Dim URL As String = "http://server/MBSDKService/MsgSDK.asmx?WSDL"
Dim myService As New LANDeskMBDSK.MBSDK
myService.Url = URL
Dim CredCache As New System.Net.CredentialCache
CredCache.Add(New Uri(myService.Url), "Basic", Cred)
myService.Credentials = System.Net.CredentialCache.DefaultNetworkCredentials

Retrieve data from excel file to make charts using the visual basic

I'm fairly new to Visual Basic. I'm using the Visual Studio 2013 and MS Excel 2010. I would like to program a code with VB that can retrieve information from the Excel .xlsx file and using that information to make charts.
Here's the edited version:
Imports System.Reflection
Imports Excel = Microsoft.Office.Interop.Excel
'Add reference Assemblies, Framework, System.Windows.Forms.DataVisualization
'Imports System.Windows.Forms.DataVisualization.Charting
Public Class Form1
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
Dim excelApp As Excel.Application
Dim excelWB As Excel.Workbook
Dim excelWS As Excel.Worksheet
Dim FNameRng As Excel.Range
Dim AveRng As Excel.Range
Dim AveCLRng As Excel.Range
Dim AveUCLRng As Excel.Range
Dim FNameArry As New ArrayList()
Dim AveArry As New ArrayList()
Dim AveCLArry As New ArrayList()
Dim AveUCLArry As New ArrayList()
excelApp = CreateObject("Excel.Application")
excelApp.Visible = False
'Open the Workbook
excelWB = excelApp.Workbooks.Open("C:\Users\Joesph\Documents\Charts\Control Limit\18x17 - 10 mil stop.xlsx")
excelWS = excelApp.Sheets("18x17 - 10 mil stop")
'Set the Range for File Name
FNameRng = excelWS.Range("A2", excelWS.Range("A2").End(Excel.XlDirection.xlDown))
'Set the Range for Average Data
AveRng = excelWS.Range("B2", excelWS.Range("B2").End(Excel.XlDirection.xlDown))
AveCLRng = excelWS.Range("H2", excelWS.Range("H2").End(Excel.XlDirection.xlDown))
AveUCLRng = excelWS.Range("I2", excelWS.Range("I2").End(Excel.XlDirection.xlDown))
'Store Range as Array
FNameArry.Add(FNameRng.Value)
AveArry.Add(AveRng.Value)
AveCLArry.Add(AveCLRng.Value)
AveUCLArry.Add(AveUCLRng.Value)
Me.CenterToScreen()
Me.WindowState = FormWindowState.Maximized
Chart1.Titles.Add("Title1")
Chart1.Titles(0).Text = "Average"
Chart1.Titles(0).Font = New Font("Garamond", 24, FontStyle.Bold)
Chart1.Series("Series1").XValueMember = "FNameArry"
Chart1.Series("Series1").YValueMembers = "AveArry"
Chart1.Series("Series1").YValueMembers = "AveCLArry"
Chart1.Series("Series1").YValueMembers = "AveUCLArry"
End Sub
End Class
So, I store the Excel range into an arraylist. I used the array as the Chart points. The program now can run without any error, but it display nothing other than the chart title. What did I do wrong here? Do I have to loop the array for the chart to display the X and Y axis? Any help would be appreciated. Thank you!
Here it is. I am using the OLE db driver to get data out of xlsx instead of Interop. I am also using 3 series instead of a single one with multiple Y values.
Imports System.Windows.Forms.DataVisualization.Charting
Imports System.Data
Imports System.Data.OleDb
'The Excel file name
Dim fileName As String = "YourExcelData.xlsx"
'connection string for Xlsx files - Microsoft ACE OLEDB 12.0
'Connect to Excel 2007 (and later) files with the Xlsx file extension.
'That is the Office Open XML format with macros disabled.
' "HDR=Yes;" indicates that the first row contains columnnames, not data.
'"HDR=No;" indicates the opposite.
'"+fileNameString+" remove String from it as defind above
Dim sConn As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source="+fileNameString+";Extended Properties=""Excel 12.0 Xml;HDR=YES"";"
Dim myConnection As New OleDbConnection(sConn)
myConnection.Open()
' The code to follow uses a SQL SELECT command to display the data from the worksheet.
' Create new OleDbCommand to return data from worksheet.
' change range
Dim myCommand As New OleDbCommand("Select * From [data1$A2:I2500]", myConnection)
' create a database reader
Dim myReader As OleDbDataReader = myCommand.ExecuteReader (CommandBehavior.CloseConnection)
' Populate the chart with data in the file
' can also use Chart.DataBindTable
Chart1.Series(0).Points.DataBindXY(myReader, "FNameArry", myReader, "AveArry")
Chart1.Series(1).Points.DataBindXY(myReader, "FNameArry", myReader, "AveCLArry")
Chart1.Series(2).Points.DataBindXY(myReader, "FNameArry", myReader, "AveUCLArry")
' close the reader and the connection
myReader.Close()
myConnection.Close()