Interaction with .bat file in VBA - vba

I am interacting with a .bat file launched in my VBA code. The shell is open and I managed to send a few commands however some other commands fail like F9, DOWN and UP.
Here is my chunk of code :
Sub OpenBrice()
Path = "F:\Brice\valpp"
ChDir Path
Shell Path & "\Brice.bat", vbNormalFocus
'Wait during opening BRICE
Wait (2)
'PASS
SendKeys "123"
Wait (1)
'Press Enter:
SendKeys "~"
Wait (1)
'Update current date
SendKeys "O"
Wait (1)
SendKeys "F"
Wait (1)
SendKeys (Format(Now(), "ddmmyy"))
Wait (1)
SendKeys "{ESC}"
Wait (2)
SendKeys "{F9}"
The problem happens on the last line, {F9} doesn't work, as well for {DOWN} or {UP}..
Further in the code, the line : SendKeys "{F8}" works perfectly...
I suspect a bad configuration of the shell or something similar ? Thanks a lot!
P.S : I am just testing some code, I know that I should declare all my variable and use Option Explicit

Related

Open Explorer Maximized with Focus and Highlight File from Access VBA

I am trying to open Windows Explorer and highlight a file.
I am using:
Private Sub cmdLoadStl_Click()
Dim shellCmd As String
shellCmd = "explorer.exe /select, """ & Me.txtPath & """,vbMaximizedFocus"
Debug.Print shellCmd
Shell (shellCmd)
End Sub
This works as expected except the window opens minimized.
I have tried this on several Win7 machines running Access 2016 and two Win10 machines, one running Access 2013, the other running Access 2016.
Is there any way to get the window to open maximized?
Edit: More information - If I paste the command generated by debug.print in my code to a command prompt and run it, the explorer window opens maximized, with the file highlighted, as it should.
The command generated from vba looks like this.
explorer.exe /select, "C:\Users\user\Desktop\filename.txt",vbMaximized
Thanks.
Try like this:
shellCmd = "explorer.exe /select, """ & """,vbMaximizedFocus
shell shellcmd,vbMaximizedFocus
The second (optional) algorithm of shell is the focus. vbMaximizedFocus opens it maximized:

How to automatically toggle Airplane mode on Windows

On my laptop I can toggle Airplane mode manually by pressing FN+F12, I want to do the same thing automatically from VB6 project or VBA.
I did a lot of search and only found answers about Enable/Disable wireless adapter or using Sendkeys for Windows 8:
Dim WSh As Object
Set WSh = CreateObject("Wscript.Shell")
WSh.Run "C:\WINDOWS\system32\rundll32.exe %SystemRoot%\system32\van.dll,RunVAN", , True
Sleep 200
WSh.SendKeys " "
Sleep 1000
WSh.SendKeys "{ESC}"
But this code is not reliable and I don't think it will work on Windows 7 or Windows 10.
So my question is: Is there any reliable way to automatically toggle Airplane mode on Windows.
I do not have a function key on my keyboard, and this is not tested, but just an idea - why don't you try like this:
Sub SetMode()
CreateObject("Shell.Application").MinimizeAll
Application.SendKeys "{F12}" 'Try a way to refer the function key
End Sub
Another possible option is something like this, depending on your Windows:
Option Explicit
Public Sub TestMe()
Application.SendKeys ("^{ESC}")
Application.Wait Now + TimeValue("00:00:01")
SendKeys ("{s}")
SendKeys ("{e}")
SendKeys ("{t}")
SendKeys ("{t}")
SendKeys ("{i}")
SendKeys ("{n}")
SendKeys ("{g}")
SendKeys ("{s}")
SendKeys "~", False
Application.Wait Now + TimeValue("00:00:01")
SendKeys ("{a}")
SendKeys ("{i}")
SendKeys ("{r}")
Application.Wait Now + TimeValue("00:00:01")
SendKeys "~", False
Application.Wait Now + TimeValue("00:00:01")
SendKeys "~", False
End Sub
The ~ sign is for ENTER, and the ctrl+escape simulates the windows key on your keyboard. After you reach what you want you can navigate with tabs and arrows.
Solution 1 : SendKeys
AFAIK the Fn key on a keyboard is not intercepted by Windows, it is a hardware mapping to a function key ie. "Volume Up".
Now the problem with that is that the "shutdown/enable wifi" key sends a signal to the hardware to power off the card.
So that's that for the SendKey, there is no virtual key for "Wireless off/on" (although there is one for "volume up").
Solution 2 : The Windows 8 API
Now the other approach would be to use the Windows 8 API here https://msdn.microsoft.com/en-us/library/windows/hardware/hh406627(v=vs.85).aspx and more specifically the following interfaces :
IMediaRadioManager
IRadioInstance
IRadioInstanceCollection
IMediaRadioManagerNotifySink
This should allow you to get the radio for bluetooth, wifi, ... as well as the "airplane mode" then shut them down, but I've never tried to use that with VBS.
Solution 3 : Using WMI queries
Using WMI queries you can basically access anything in your machine, including network cards.
The class you are looking for is "Win32_NetworkAdapter" and all docs can be found here : https://msdn.microsoft.com/en-us/library/aa394216(v=vs.85).aspx
Here is a little sample code that will list the current network adapters, you can customize this to save which ones were enabled before you run the script to be able to re enable them after.
' connects to the WMI server of the local machine
Set objConnection = GetObject("winmgmts:" _
& "{impersonationLevel=Delegate," _
& "authenticationLevel=PktPrivacy}!" _
& "\\localhost\root\cimv2")
' gets a list of all the network adapters in the system
Set objNetworkAdapters = objConnection.ExecQuery("SELECT * FROM Win32_NetworkAdapter")
' loops through all network adapters
For Each objCurrentNetworkAdapter in objNetworkAdapters
' objCurrentNetworkAdapter.Disable
' objCurrentNetworkAdapter.Enable
WScript.Echo objCurrentNetworkAdapter.Name
Next
Remark :
You are basically not supposed to access the "Airplane mode" from code as it is a user privilege to do so, imagine if someone builds an app that turns on roaming and data connection then starts updating while you are abroad...

VBA code to pass username & password

I'm trying to update some data into a SharePoint document and while trying this in local environment I do not face any issue.
But when I try to do the same in virtual desktop, I couldn't make it. I'm being populated with Windows Alert to key-in username & password. I've tried using 'SendKeys' for this scenario, but it doesn't make sense.
....
SendKeys "abc\ATX123",5
SendKeys "Password1",5
SendKeys "{ENTER}",5
....
This snippet is just passing 'ENTER' without entering ID & Pwd. Can anyone suggest me some possible solution, please?
Finally, I've found a way to achieve this requirement,,,,, bit indirect, but that was the only way I could find at the end.
What I did is simple - just created one windows scripted file 'Logon.vbs' to handle that popup screen and called the vbs in VBA.
Refer to the sample below, if you're looking for something like this:
Windows Script:
'Creating an script object
Set oWSH = WScript.CreateObject("WScript.Shell")
'Activating alert screen
oWSH.AppActivate ("Windows Security")
'Passing the value UserName/UserID
oWSH.SendKeys "USERNAME" 'ensure to complete the username with apropriate domain e.g., abc/A123456
'Changing the focus to password textbox
oWSH.SendKeys "{TAB}"
'Passing the value password
oWSH.SendKeys "PASSWORD"
'Clicking enter to complete the screen
oWSH.SendKeys "{ENTER}"
'Releasing the script object
Set oWSH = Nothing
VBA code to call the VBS script - Logon.vbs:
Shell "WScript C:\Users\ABC\Desktop\Logon.vbs", vbNormalFocus
First of all you'll want to SendKeys "yourString", Boolean. As I know the SendKeys command wants a True or a False as second input.
You could also try "tabbing" from a field to another:
SendKeys "abc\ATX123", True
SendKeys "{TAB}", True
SendKeys "Password1", True
SendKeys "{ENTER}", True
if the first one didn't get get written, maybe the focus is on another component of the userform. Try "tabbing" to find out if your "Username" textbox is yet activated as the UserForm appears. In case it isn't you could also try to set some focus

How to click on this particular button from VBA?

I have a simple VBA code (see below), that goes to a webpage, selects some value, clicks the “Begin download” button, and then saves the file. The problem is I am stuck at the “clicking the download button” part. Can someone help?
Here is the code:
Sub Treasury_Auc_Notes()
Dim IE As Object
Set IE = Nothing
Set IE = CreateObject("InternetExplorer.Application")
IE.Visible = True
IE.Navigate "http://www.treasurydirect.gov/RI/OFAuctions?form=ndnld&typesec=notes"
While IE.Busy
DoEvents
Wend
IE.Document.All.Item("begYr").Value = "2012"
With IE.Document.getElementsByName("cols")
.Item(0).Checked = True
End With
'Click "Begin download" button (this is where I am stuck)
'Choose Save Open or Cancel (I haven’t got to this part yet)
ActiveWorkbook.SaveAs Filename
End Sub
This one's tricky, and due to restrictive security on my laptop, I'm not able to verify this 100%, but try:
While IE.ReadyState <> 4
DoEvents
Wend
IE.Document.All.Item("begYr").Value = "2012"
With IE.Document.getElementsByName("cols")
.Item(0).Checked = True
End With
Dim ele As Object
For Each ele In IE.Document.Forms
If ele.Action = "/RI/OFAuctions" Then
ele.Submit
Exit For
End If
Next
You may have to use SendKeys (I think Application.SendKeys "o") method to open the file then use VBA to save the ActiveWorkbook to the desired location. I'm not able to test SendKeys for reasons mentioned below.
Or, I'm pretty sure there is a WinAPI functions that can do this more reliably than SendKeys. You'll need to get the hWnd of the Save dialog and do some other stuff to force it to open/save. This is fairly advanced VBA that I probably have a reference to somewhere, but rarely need to use it. If you have trouble with this particular part, I would urge you to ask a separate question "How to get the hWnd of File Save dialog and download file from IE" or something like that.
NOTE: I can't test the SendKeys method. When I use the above code, I am fairly certain the file is being downloaded, but it is going to a temporary folder that is hidden, and difficult to find. In any case, it does appear to be downloading with some manual intervention. I get this warning:
I click to ignore that (I have no idea how to automate this part, I'm just trying to validate that the form .Submit method actually worked), and after some creative searching (temporary internet files get dumped in a strange/hidden folder usually) I verify the file is downloaded, although it is showing as a TXT extension instead of CSV.
If instead of using VBA, I click on the button manually, and I choose to "open" the file opens as CSV and has the same path to that temporary internet location.

Sending Multiple Words to Another Program

How would I output a sentence with VB.NET?
Example: Your program and Internet Explorer are open, your program outputs "http://stackoverflow.com" and presses "{ENTER}", and it will go to the page.
Example: An auto-talking bot for MSN.
If you mean "send a string to a running program", I think you're looking for SendKeys
Edit
SendKeys takes a string argument (that's why it's named SendKeys, not SendKey), so yes, you can send "sentences".