Is it possible to change internet connection (e.g. from WiFi to Cable) with VBA? - vba

For reporting purposes, I'm importing data from various sources on the net into an Excel Workbook.
Problem is: while some of the stuff I want is on my company's private network (requiring cable connection), some of the URL/webservices I want to connect to are not allowed by my company's proxy (via cable connection).
Thus, I have to use another connection without proxy (via WiFi) to get those to work.
This WiFi connection is always active on my computer, but it requires me to manually unplug the cable for half of my imports and to plug it back to access files on my company's network for the other half...
I wonder if there is a way with VBA to tell the computer to use cable / WiFi according to what I need.
I am working on a Windows XP Pro computer with Excel 2010/VBA. Please help!

Found Two ways to enable or disable i.e change internet adapter connection from VBA:
'adjust these according to your need i.e change adapter name, change enabled or disabled parameter, change path, change file name etc. VBS approach is long but gives more control. Bat approach is short but limited IMO
1 Using vbs Source link :
'file name: asdf.vbs
'Get and disable all physical wired adapters (AdapterTypeID=0) (Ethernet 802.3)
'Wscript.Echo "test"
Set wmi = GetObject("winmgmts:root\CIMV2")
Set adapters = wmi.ExecQuery("Select * from Win32_NetworkAdapter where _
AdapterTypeId=0 AND NetConnectionID IS NOT NULL",,48)
For Each adapter in adapters
With adapter
WScript.Echo "available: " & .Availability & " enabled: " & .NetEnabled & " netconStatus: " & .NetConnectionStatus & " status: " & .Status & " netconnID: " & .NetConnectionID & " adType: " & .AdapterType
'adapter.disable()
'adapter.enable()
End With
Next
' Get and disable all physical wireless adapters (AdapterTypeID=9) (wireless)
2 Using bat Ref link1 and Ref link2 :
'file name: switch_lan6.bat
#echo off
start /MIN cmd.exe /c "netsh interface set interface name="Local Area Connection 6" admin=disabled"
Running these inside excel vba:
Shell "wscript ""C:\Users\USER\Desktop\asdf.vbs""", vbNormalFocus
or,
Call Shell(ThisWorkbook.Path & "\switch_lan6.bat", 0)

Related

Running SQL Within An Open Workbook

I'm trying to use VBA to perform some SQL operations within an open workbook. If I open the file as a read only (i.e. from an email) the code runs without issue, but if I save it locally to my desktop I get a run-time error "Cannot update. Database or object is read-only". Below is a snippet of the code I'm trying to run
Set CSVconn = New ADODB.Connection
CSVconn.ConnectionString = _
"Provider=Microsoft.ACE.OLEDB.12.0;" & _
"Data Source=" & ThisWorkbook.FullName & ";" & _
"Extended Properties='Excel 12.0 Xml;HDR=yes';"
CSVConn.Open
tmprs.ActiveConnection = CSVconn
tmprs.Source = "SELECT DISTINCT [X] FROM [Range]"
tmprs.Open
Range(X).CopyFromRecordset tmprs
CSVconn.Close
I believe the problem lies with the "ThisWorkbook.FullName" portion of the connection string since the code works on my coworkers' PCs and off our company drive. The file is saved locally and the "Files On Demand" setting for OneDrive is turned off, but the file path is still listed as running through https://sharepoint.com. I've used the split function to rebuild the SharePoint address as a local C drive one (which will open the workbook if I paste the address in file explorer), but running it in VBA throws an error that the file path is not valid. I've tried switching the connection to a GUID, but Windows shut down the Scriptlet.TypeLib function as a security measure and I can't seem to get their workaround code to run. Anyone know how to fix the CSVConnection issue or how to assign a randomly generated GUID to an open workbook using VBA?

System.AccessViolationException occurs with MS Access databases just over WiFi connection

I'm developing a desktop application for my company (it's just a prototype, actually) for bringing simple services to production department (tool and process instructions, presence records, product traceability, etc).
I'm using VB.net and wpf; some MS Access databases are the backend. It uses Access Database Engine 2016.
I have a simple function used to update database records, here's it:
Public Function UpdateDatabaseRecord(DatabaseNumber As Integer, tblName As String, SearchInColumn As String, SearchBy As String, UpdateColumn As String, UpdateTo As String) As Integer
Try
Using ServerConnection As New OleDbConnection(ConnectionSelector(DatabaseNumber))
Dim CommandString As String
If SearchInColumn <> "ID" Then
CommandString = "UPDATE [" & tblName & "] SET [" & UpdateColumn & "]=#UpdateColumn WHERE [" & SearchInColumn & "] = " & DQ & SearchBy & DQ
Else
CommandString = "UPDATE [" & tblName & "] SET [" & UpdateColumn & "]=#UpdateColumn WHERE [" & SearchInColumn & "] = " & SearchBy
End If
Dim CommandUpdate As New OleDbCommand(CommandString, ServerConnection) With {.CommandTimeout = 10000}
With CommandUpdate.Parameters
.AddWithValue("#UpdateColumn", UpdateTo)
End With
ServerConnection.Open()
CommandUpdate.ExecuteNonQuery()
ServerConnection.Close()
End Using
UpdateDatabaseRecord = 0
SetCentralTimeStamp(DatabaseNumber, tblName)
Catch ex As Exception
Msg(Reflection.MethodBase.GetCurrentMethod.Name & NewLine & ex.Message & NewLine & "Err. Number " & Err.Number, "Database Error", MessageBoxButton.OK, MessageBoxImage.Error)
UpdateDatabaseRecord = Err.Number
End Try
End Function
Sometimes the application uses this function in the main thread; sometimes it runs it from scheduled task (clocked by a forms.timer every two minutes). This tasks aren't obviously in the main thread, but the code has been used succesfully for a couple of months with computers directly connected to company network via LAN cable. Recently I tried my application on a laptop connected via wifi to the company network, and I get an exception that's crashing my app. I installed VS on that laptop to debug the code, and I found that an AccessViolationException is raised on line "CommandUpdate.ExecuteNonQuery".
I tried to google it but it seems that this exception shouldn't be raised from managed code.
The error occours only with laptop connected via wifi.
Also, another function reads data from the databases: sometimes I get the same error in it, in the line where the connection is being opened (connection.open).
What should I check?
Thanks in advance.
ps "ConnectionSelector" is a simple function which returns the appropriate ConnectionString based on database number.
EDIT 1 - The WiFi network is created plugging directly a LAN cable from the actual wired network, using a common wireless router. IP addresses are automatically assigned and the connection works, since the app is able to get data from databases.
I solved the problem myself and I'm posting here the solution I found: I hope it will help someone in the future.
I resolved simply enabling all OLEDB Services for the database connection. It looks like connection pooling really help stability and performance, especially when using a wifi network like I'm forced to do. If you want, Google "OLEDB Services" and look for enabling them all.

Close VB.NET app when main VB6 form is closed

I have 2 VB6 application which may launch the same VB.NET application (same exe) via a subMenu. The VB6 code to start this application is a Shell command :
ret = Shell(exe, 1)
My problem is when the user exit the main application (VB6), it won't close the VB.NET application if he opened it.
I tried to use the Taskkill command. It effectively kills the application, but it kills this app for every users on the server !!
I need to do it only for the current user. Can anyone help ?
EDIT : I found some documentation with Taskkill.
It seems that i can precise a user and a domain in the command. I use the following code :
Dim cmdShell As String
quote = Chr$(34)
cmdShell = "taskkill.exe /f /fi " & quote & "USERNAME eq " & _
LCase(connection_User) & quote & " /im " & exeToKill
If someone have a better idea, i'm in :)

Possibility of VB.net and VBScript

Is it possible to include in a VB.net 2008 Project a VBScript (test.vbs) and run it if its while the processing necessary? But the main thing is it should be possible to BUILD just one .exe.
If so, can you also receive values / arguments from the VBS file?
Here is an example, although it's pointless, but it is used for unterstanding:
VB.net -> exe is running
the exe runs please_find_the_coputername.vbs
The script please_find_the_coputername.vbs -> obtained the computer name and sends this variable to VB.net
VB.Net displays the computer name via Msgbox().
Note: I know that I can read out the computer name with VB.net but this example is only for understanding my questions.
Edit:
HI #maxedev thank you for your answer.
Wow.. its nice trick.
But I want only to do this VBScript code in VB.net:
Dim strComputer
strComputer = "LP-BKR"
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\" _
& strComputer & "\root\cimv2")
Set colComputer = objWMIService.ExecQuery ("Select * from Win32_ComputerSystem")
For Each objComputer in colComputer
Wscript.Echo "Logged-on Domain: " & objComputer.Domain
Wscript.Echo "Logged-on UserName: " & objComputer.UserName
Wscript.Echo "Logged-on ComputerName: " & objComputer.Name
Next
set objWMIService = Nothing
set colComputer = Nothing
I searched the whole day to get the same Value... but didn't find anything. That's why I decide to do that in this way. But if I think, the trick with clipboard is risky. It pushes the still clipboard text away. How can I realize it?
I'm not sure exactly what you're trying to accomplish, but you could write to a text file and then read it through vb.net - or you could do something like this post to use the clipboard to pass info ie :
VBS:
Set WshShell = WScript.CreateObject("WScript.Shell")
WshShell.Run "cmd.exe /c echo hello world | clip", 0, TRUE
VB.NET:
MessageBox.Show(Clipboard.GetText)
--shows "hello world"
One solution would be to add a reference to the MS Script Control:
http://msdn.microsoft.com/en-us/library/aa227400(v=vs.60).aspx
Using that, you can add literally add code (VBScript) with the AddCode() method then run it and get the output back. I have a tiny example here.
Windows automatically provides the information you're looking for in environment variables:
%USERNAME% -> username of the logged in user
%USERDOMAIN% -> WINS name of the domain the user is logged into
%USERDNSDOMAIN% -> FQDN of the domain the user is logged into
%COMPUTERNAME% -> hostname of the computer

Getting the size of a remote folder via classic ASP

I'm trying to something pretty simple but am having headaches with it. I'm pretty sure all I have here is a permissions issue I don't know how to solve but I could be wrong.
Here is my scenario...
I have 3 servers...
Server A - Web Server (Windows 2003) - Anonymous Access Enabled
Server B - Red 5 Media Server
Server C - NAS
The website on Server A allows for recording/uploading of video to Server B where the video is processed/transcoded.
A Cron job on Server B then moves the videos over to Server C for storage.
Users can then watch their videos from Server A via a virtual directory thats been set up in IIS that points to Server C and connects as a domain user account.
I need to some how use the ASP File System Object to get the size of a folder on Server C that contains the videos.
I've mapped the parent folder of the folder on Server C where the videos are stored to a drive letter on Server A using a UNC path (\servername\videos).
I've tried using the FileSystemObject's folderExists() method for debugging purposes and it returns false if I pass in the mapped letter drive or a UNC path. It gives a path not found error. Just to be sure I did a response.write of the path being passed into the folderExists() method and it is the correct path. All of this leads me to believe this is really a permissions issue which I just don't know how to solve.
Thanks,
Ryan
Mapped network drives are no use to you in ASP on IIS6 since they are part of a user profile. User profiles are not fully loaded in services like IIS6.
Assuming a pure ASP environment (you can't install other dlls etc) then you will need the anonymous user to have access to the network share where the videos are stored and use the UNC path.
Now typically the IUSR account is local guest account which has no access to the network. You will need to create a user on the domain that the NAS belongs to and specify that users credentials as the anonymous user account for those pages that need to do your "Get Size" task ( you don't need change anonymous user for the whole application).
The foregoing assumes Server A is a member of the same domain as Server C. If not then you need to create user on the domain the Server A belongs to as well that mirrors the one on Server C including its password (or jump through trust relationship hoops).
With that in place you can go ahead and use FileSystemObject.
You need to work with the FSO.Drives collection to get to your NAS. Have a look at this article (just googled it but it seems ok):
http://www.stardeveloper.com/articles/display.html?article=2001050301&page=1
Try running this and seeing if you drives are available, should help narrow down if its a permissions problem
<%
Dim fso
Set fso = Server.CreateObject("Scripting.FileSystemObject")
Dim drives
Set drives = fso.Drives
Dim isReady
For Each drive in drives
isReady = drive.IsReady
If isReady Then
Response.Write "DriveLetter: " & drive.DriveLetter & "<br>"
Response.Write "Path: " & drive.Path & "<br>"
Response.Write "FileSytem: " & drive.FileSystem & "<br>"
Response.Write "TotalSize: " & drive.TotalSize & "<br>"
Response.Write "FreeSpace: " & drive.FreeSpace & "<br>"
Else
Response.Write "Driv Letter: " & drive.DriveLetter & "<br>"
Response.Write drive.Path & "<br>"
Response.Write "No other information available."
End If
Next
%>
Have a play with that and see if you are still having problems, if so we will dig a bit deeper :)
Not sure if this is the right thing to do but to remedy this I had to map the network drive via ASP (as the IUSR_machine) account like so...
dim objNetwork
Set objNetwork = CreateObject("WScript.Network")
objNetwork.MapNetworkDrive "X:", "UNC path", "profile", "user", "password"
objNetwork.RemoveNetworkDrive "X:"
set objNetwork = nothing
Then I was able to access the mapped drive letter (X in this case) via the FileSystemObject.