I keep getting an error:
System.NullReferenceException: Object reference not set to an instance
of an object.
Everytime I run the application outside the IDE, but for some magical reason, it works fine inside the IDE. I am definitely sure the error is caused by this code as the app ran smoothly when I removed it:
Public Function GetCommonFolder() As String
On Error GoTo ErrH
Dim winPath As String = Environment.GetFolderPath(Environment.SpecialFolder.CommonApplicationData)
Dim commonfolderpath As String
commonfolderpath = Replace(winPath & "\MyApp Data", "\\", "\")
If My.Computer.FileSystem.DirectoryExists(commonfolderpath) = False Then
System.IO.Directory.CreateDirectory(commonfolderpath)
End If
GetCommonFolder = commonfolderpath
Exit Function
ErrH:
GetCommonFolder = ""
Msgbox("Error retrieving common folder")
End Function
Does anyone here know what is causing this annoying problem?
It seems like the user that you run the program on outside the IDE doesn't have access to the common application data folder. Try executing it by "Run as administrator". Are you running on Windows Vista or newer? Maybe you have to require UAC elevation?
Related
I created a button and a menu item in vb.net (.NET 6). I found several answers here on SO that say the process to launching a webpage from such an event can be launched with this code:
Dim webAddress As String = "http://www.example.com/"
Process.Start(webAddress)
However, trying launch the code, I'm given the error of "system cannot find the file specified".
Looking more into it, I know that .NET 6 is running a bit differently and changed the code to the following:
Using link As New Process()
link.StartInfo.UseShellExecute = True
link.Start(New ProcessStartInfo("https://example.com"))
End Using
But still to no avail, and I am given the same error. "System cannot find the file specified." I can run addresses via the regular Windows Run prompt... but the program still cannot launch.
Following Jimi's comment to my original question, I changed the Sub to the following:
Sub LaunchWebsite(strWebpageURL As String)
Using Process.Start(New ProcessStartInfo(strWebpageURL) With {.UseShellExecute = True})
End Using
End Sub
Using this, the webpage launched in my desktop's default browser with no problem.
You can use
Respone.Redirect("http://www.example.com/")
or use javascript in server side code
Dim url As String = "http://www.example.com"
Dim s As String = "window.open('" & url + "', 'popup_window', 'width=300,height=100,left=100,top=100,resizable=yes');"
ClientScript.RegisterStartupScript(Me.GetType(), "script", s, True)
Above code open webpage in new popup window.
Regards
Aravind
I'm calling a C# WebService method called getInterventions() on a VBA Access 2003 application through a custom DLL. The signature of this method is as follows:
List<Item> getInterventions(string, string, string, string, string, string)
Item is a custom defined class.
When I try to retrieve the result of getInterventions() on VBA Access code, it pops a VBA Runtime error 242 : object required
The following is my code:
Dim WsObject As Object
Dim result As Object
Set WsObject = CreateObject("Namespace1.Path.To.Class") 'This isn't the actual DLL path as I cannot share that
'Set result = WsObject .getSingleIntervention("123, "0", "123456789", "") ' this works
Set result = WsObject .getInterventions("", "", "123456789", "", "", "") 'this doesn't work
If result Is Nothing Then
'do some stuff
Else
'do some other stuff
End If
getSingleIntervention() is a similar method which returns a single object rather than a list of objects. Returning the result of this method works without issues (see commented line). This proves that both the WS & DLL calls work. This method is defined as follows:
Item getSingleIntervention(string, string, string, string)
I have tested calling getInterventions() directly from the C# code via Visual Studio 2015 with the same parameters I'm passing in my VBA code and it worked. This proves that it's not an issue with parameters or the method content.
My conclusion:
I am guessing it's something to do with the fact that I can't simply store a C# List of objects into a VBA Object.
Any help would be appreciated, thank you.
Please, automatically add mscorlib.tlb reference, running the next code:
Sub addMscorlibRef() 'necessary to use ArrayList
'Add a reference to 'Mscorlib.dll':
'In case of error ('Programmatic access to Visual Basic Project not trusted'):
'Options->Trust Center->Trust Center Settings->Macro Settings->Developer Macro Settings->
' check "Trust access to the VBA project object model"
If dir("C:\Windows\Microsoft.NET\Framework64\v4.0.30319", vbDirectory) = "" Then _
MsgBox "You need to install ""Framework version 3.5"".": Exit Sub
On Error Resume Next
Application.VBE.ActiveVBProject.References.AddFromFile "C:\Windows\Microsoft.NET\Framework64\v4.0.30319\mscorlib.tlb"
If err.Number = 32813 Then
err.Clear: On Error GoTo 0
MsgBox "The reference already exists...": Exit Sub
Else
On Error GoTo 0
MsgBox """Mscorlib"" reference added successfully..."
End If
End Sub
Then try declaring Dim result As ArrayList.
The ArrayList is the same one that is used in C#. Then, adapt the dll to use such an object. As you deduced, no any object able to be used in VBA can receive the C# list object content.
This is my first question so please go easy on me.
My company is working with Reflection for UNIX and OpenVMS and I'm building a database that interacts with the software as it is impossible for me to access the database behind the Reflection application (too many authorizations required etc...).
I'm working with MS Access 2013 right now and coding in VBA. My main issue is closing the Reflection instance in a clean manner.
The following code works fine for me :
Sub Test()
Dim strUserId As String
Dim MyObject As Reflection2.Session
Set MyObject = GetObject(Path)
strUserId = InputBox("Enter user ID.")
ContractNum = InputBox("Enter a contract number :")
With MyObject
.Visible = True
.Connect
.Transmit strUserId
.TransmitTerminalKey rcVtEnterKey
.Transmit ContractNum
.TransmitTerminalKey rcVtEnterKey
sContractNum = .GetText(1, 18, 1, 28)
'Do other shit
End With
**Exit Reflection**
Set MyObject = Nothing
End Sub
I have tried the following methods :
MyObject.Close ==> Returns : "Run-time error '438': Object doesn't support this property of method"
MyObject.Exit ==> Returns : "Run-time error '438': Object doesn't support this property of method"
MyObject.Quit ==> Returns : "Run-time error '10097': This function not available when running Reflection as a document object."
There is: MyObject.ConfirmExit = True but as it says, it only confirms and doesn't close.
Anyway I was hoping someone would help before doing a hard closing through Shell command (wouldn't be difficult to find on Google I guess).
Thank you!!
Found a way using the following code, it is quite a harsh closing but works fine for the moment :
Function TaskKill(sTaskName)
TaskKill = CreateObject("WScript.Shell").Run("taskkill /f /im " & sTaskName, 0, True)
End Function
If TaskKill("r2win.exe") = 0 Then MsgBox "Terminated" Else MsgBox "Failed"
Hope that helps
I have a VB.Net application in which I have a general method to open documents that exist on the local drive using system.diagnostics.process.
Public Shared Function OpenFileWithProcess(ByVal lsFileNameWithPath As String, Optional ByVal lPrintOption As PrintOutputOption = PrintOutputOption.Preview)
Try
Select Case lPrintOption
Case PrintOutputOption.Preview
Dim P As System.Diagnostics.Process
P = Process.Start(lsFileNameWithPath)
If Not P Is Nothing Then
Dim handle As IntPtr = P.Handle
SetForegroundWindow(handle)
End If
Case PrintOutputOption.Print
Dim Proc As New Process
Proc.StartInfo.FileName = lsFileNameWithPath
Proc.StartInfo.UseShellExecute = True
Proc.StartInfo.Verb = "Print"
Proc.Start()
End Select
Catch ex As Exception
If oSQL.Key_Developer Then
Stop
End If
Throw ex
End Try
End Function
On some computers that have Windows8 and OFfice2010, this method will not open an Excel file without Excel being open first. Instead it will error with "Run-Time Error 2147467259 (80004005). An error occurred in sending the command to the application".
If Excel is open prior to the method call, then the file opens just fine.
Some additional environment info:
- VB.NET application compiled to .Net Framework 4
- Application is deployed on Windows 7, 8 and 8.1
I could trap for the error and try to start the process again using the Excel session that hangs open after the error but I'm wondering if someone can tell me or help me figure out what is going on here.
Thank you for your time.
After recently upgrading from Excel 2010 to Excel 2013, I moved a custom add-in (.xlam) to the new Application.LibraryPath directory (C:\Program Files\Microsoft Office 15\root\office15\Library\BTRTools). There is a bit of code that launches an executable (exe) file (located in sub directory of the add-in). However, since the upgrade/move, I am not getting an error:
PrettyPrintXml.exe - Application Error
The application was unable to start correctly (0xc000007b). Click OK to close the application.
I'm obviously pretty convinced it is file permissions. I have explicitly added myself permissions with full rights to the \Library folder (and all subs). Note that I think I had to do this even with Excel 2010 (folder at C:\Program Files (x86)\Microsoft Office\Office14\Library) to make things work.
However, after all this, I'm still stuck and can not launch the exe file. Any ideas/suggestions on how to make this work?
Code is pretty standard:
Public Sub RunShellExecute(sFile As String, Optional params As String = "", Optional wait As Boolean = False)
Dim wsh As Object: Set wsh = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = wait
Dim windowStyle As Integer: windowStyle = 1
Dim exe As String: exe = IIf(Left(sFile, 1) <> """", """" & sFile & """", sFile)
Dim exeParams As String: exeParams = IIf(params <> "", " " & params, "")
Dim errorCode As Integer: errorCode = wsh.Run(exe & exeParams, windowStyle, waitOnReturn)
If errorCode = 0 Then
'// MsgBox "Done! No error to report."
Else
MsgBox "Program exited with error code " & errorCode & "."
End If
End Sub
I know your question is "Why doesn't this work", but I thought you might be interested in an alternate solution: There is a native VBA PrettyPrintXML. You need to add a reference to the MSXML library in your VBA project by clicking "Tools" ---> "References..." and then check the box next to Microsoft XML, v6.0 (or whatever version is included with your version of Office/Windows).
Please change the title of your question, because Excel VBA is able to use WScript.Shell.Run, otherwise you wouldn't be getting your error.
As for the actual issue, this looks like a 32-bit / 64-bit problem. Investigate whether the program you're calling is appropriate for your system and whether it tries to load the right DLLs.
The problem is not file permissions, then you would get a different status code.
You should use a path without spaces in it, something simple like 'C:\BTRTools'. Then it should work.