0

How to show Windows 10 notification toast from VBA

Came across above link, with below code. However seem not able to add a $variable. Tried

#    '" & sMessage & "'
 strCommand = strCommand & "; $notify.showballoontip(10,'New Chat!','" & sMessage & "',[system.windows.forms.tooltipicon]::None)"

But that gave no errors but no notification either. Below the original code from above link.Which works great

Public Sub Notify_Test()

Dim WsShell     As Object: Set WsShell = CreateObject("WScript.Shell")
Dim strCommand  As String

strCommand = "powershell.exe -Command " & Chr(34) & "& { "
strCommand = strCommand & "[reflection.assembly]::loadwithpartialname('System.Windows.Forms')"
strCommand = strCommand & "; [reflection.assembly]::loadwithpartialname('System.Drawing')"
strCommand = strCommand & "; $notify = new-object system.windows.forms.notifyicon"
strCommand = strCommand & "; $notify.icon = [System.Drawing.SystemIcons]::Information"
strCommand = strCommand & "; $notify.visible = $true"
strCommand = strCommand & "; $notify.showballoontip(10,'New Chat!','You have received New Chat!',[system.windows.forms.tooltipicon]::None)"
strCommand = strCommand & " }" & Chr(34)
Shell strCommand, vbHide
End Sub

Edit: seems that sMessage needs to be cleaned up, an Apostrophe was the bug.

Grmn
  • 542
  • 2
  • 9
  • In PS is you are combing two strings you use the plus sign not an ampersand. PS uses c# syntax, not basic. – jdweng May 18 '23 at 16:02
  • 2
    What's the content of sMessage? Make sure that quotes are escaped. – yacc May 18 '23 at 16:08
  • 1
    It had in this case indeed a Apostrophe and thus it did not work. @yacc thx – Grmn May 18 '23 at 17:52
  • @jdweng, the code in the question is VBA (Visual Basic For Applications), where `&` is used for string concatenation, which is simply being used to _build_ the string to pass to `powershell.exe` here, so the use of `&` is obviously not the problem. To be clear re "PS uses C# syntax": PowerShell uses `+` for string concatenation (too), which _happens to be_ what C# (and many other languages) use too. – mklement0 May 19 '23 at 12:42

1 Answers1

1

Make sure that quotes in sMessage are escaped. This will be required for single quotes as well as double quotes, because the command will be parsed by Powershell and the cmd shell. Doubling the quotes should do it.

Remarks from @mkelement0:
Doubling the double quote will only work in PowerShell v7+. Use \" to be safe.

Sample:

    powershell -c "write-host 'new chat!' '\"It''s here\"'"
yacc
  • 2,915
  • 4
  • 19
  • 33
  • Doubling works for `'` (which is enough here), but note that for `"` it must be ``\"`` in _Windows PowerShell_ CLI calls (`powershell.exe`); `""` only works in [_PowerShell (Core) 7+_](https://github.com/PowerShell/PowerShell/blob/master/README.md) (`pwsh.exe`) – mklement0 May 19 '23 at 12:38