How do I display a messagebox with unicode characters in VBA? - vba

I have a string containing unicode characters in VBA.
I want to display that string in a message box containing it.
However, instead of the string, the message box only contains a questionmark.
MCVE:
Dim s As String
s = ChrW(5123)
MsgBox s

MsgBox is not compatible with non-ANSI unicode characters.
We can display message boxes with the WinAPI MessageBoxW function, however, and that is .
Let's declare that function, and then create a wrapper for it that's nearly identical to the VBA MsgBox function:
Private Declare PtrSafe Function MessageBoxW Lib "User32" (ByVal hWnd As LongPtr, ByVal lpText As LongPtr, ByVal lpCaption As LongPtr, ByVal uType As Long) As Long
Public Function MsgBoxW(Prompt As String, Optional Buttons As VbMsgBoxStyle = vbOKOnly, Optional Title As String = "Microsoft Access") As VbMsgBoxResult
MsgBoxW = MessageBoxW(Application.hWndAccessApp, StrPtr(Prompt), StrPtr(Title), Buttons)
End Function
This function is only compatible with Microsoft Access. However, for Excel you can swap Application.hWndAccessApp with Application.hWnd to make it work. For other VBA compatible applications, you'll have to find the appropriate way to get the hWnd.
You can use it like MsgBox, as long as you don't use the context-dependent help functionality:
Dim s As String
s = ChrW(5123)
MsgBoxW s

An alternative could be my ModernBox:
MsgMox ChrW(5125) & ChrW(5123) & ChrW(5121) & ChrW(5130), vbInformation, "Unicode"
Display:

Related

Open Hyperlinks in Access

I have a table of products where there is say a pdf for a specific products user manual. I'm storing the model name and it's file path in my products table (in Access). I've created a form in Access that allows the user to search by product name and it narrows down the number of files and shows the results from the search in a list box. However my biggest problem is opening the actual PDF. It opens the file, but I have to store the file path exactly how it is and the path of the files are long. Is there a way to open the PDF hyperlinks without using the Followhyperlink command? Or is there a way that I can show only the file name of the pdf in my list box rather than the entire path name? If I change the display text in my products table it doesn't open the hyperlink, I get an error. Any help would be greatly appreciated!
Application.FollowHyperLink() has problems with security, especially when opening files on a network drive. See e.g. here: http://blogannath.blogspot.de/2011/04/microsoft-access-tips-tricks-opening.html
A better method is the ShellExecute() API function.
Essentially it looks like this (trimmed from http://access.mvps.org/access/api/api0018.htm ):
' This code was originally written by Dev Ashish.
' http://access.mvps.org/access/api/api0018.htm
Private Declare Function apiShellExecute Lib "shell32.dll" _
Alias "ShellExecuteA" _
(ByVal hwnd As Long, _
ByVal lpOperation As String, _
ByVal lpFile As String, _
ByVal lpParameters As String, _
ByVal lpDirectory As String, _
ByVal nShowCmd As Long) _
As Long
Public Const WIN_NORMAL = 1 'Open Normal
Private Const ERROR_SUCCESS = 32&
Public Function fHandleFile(stFile As String) As Boolean
Dim lRet As Long
lRet = apiShellExecute(hWndAccessApp(), "Open", stFile, vbNullString, vbNullString, WIN_NORMAL)
If lRet > ERROR_SUCCESS Then
' OK
fHandleFile = True
Else
Select Case lRet
' Handle various errors
End Select
fHandleFile = False
End If
End Function
Now for your listbox:
Set it to 2 columns, the first being the model name, the second the file path.
Set the column width of the second column to 0, so it will be invisible.
And in the doubleclick event, call fHandleFile with the second column (file path):
Private Sub lstManuals_DblClick(Cancel As Integer)
Call fHandleFile(Me.lstManuals.Column(1))
End Sub

SendMessage - Passing a string from VB6 to VB.NET

Good afternoon,
I am attempting to use SendMessage to pass a string from a VB6 EXE, to a .NET 2013 EXE. I know that the message is getting in to the .NET EXE, because I'm able to set a breakpoint on it and it comes up when I call SendMessage from the VB6 EXE. The problem I am having is retrieving the string.
This is how I am attempting to do it:
VB6 Code:
Option Explicit
Private Declare Sub CopyMemory Lib "kernel32" Alias "RtlMoveMemory" (dest As Any, Source As Any, ByVal bytes As Long)
Private Declare Function FindWindow Lib "user32" Alias "FindWindowA" (ByVal lpClassName As String, ByVal lpWindowName As String) As Long
Private Declare Function SendMessage Lib "user32.dll" Alias "SendMessageA" (ByVal hwnd As Long, ByVal msg As Long, wParam As Long, lParam As Any) As Long
Private Const APPVIEWER_OPEN = &H400
Private Sub Command1_Click()
Dim hwndAppViewer As Long
Dim bytBuffer(1 To 255) As Byte
Dim sParams As String
Dim lStringAddress As Long
hwndAppViewer = FindWindow(vbNullString, "DotNetReceiver")
If hwndAppViewer > 0 Then
sParams = "STRINGDATA"
CopyMemory bytBuffer(1), sParams, Len(sParams)
lStringAddress = VarPtr(bytBuffer(1))
SendMessage hwndAppViewer, APPVIEWER_OPEN, Me.hwnd, lStringAddress
End If
End Sub
Here is the .NET code:
Imports System.Runtime.InteropServices
Public Class Form1
Protected Overrides Sub WndProc(ByRef m As Message)
Dim sPolicyInformation As String
If m.Msg = &H400 Then
sPolicyInformation = Marshal.PtrToStringAnsi(m.LParam)
Else
MyBase.WndProc(m)
End If
End Sub
End Class
The problem comes when I try and retrieve the string. I am getting a blank string. I noticed that the number in the VB6 lStringAddress and the number in .NET m.lParam are completely different, so I must be missing something about how I'm passing the address through lParam.
Any ideas what I might be missing?
Thank you.
You are sending an ANSI string to VB.NET. VB6 was designed for all MS's OSs and 9x wasn't unicode. So all strings passed to API calls will be converted to ANSI. Windows will convert that ANSI string to unicode for the VB.NET program when it recieves it.
Use the sendmessagew function and send the first element of a byte array that's null terminated.
Dim MyStr() as byte
MyStr = "cat" & chrw(0)
The pass only the first element to SendMessageW ie MyStr(0). Windows API uses null terminated C strings. COM and VB6 use BStr (a size header and a non null terminated string).
When passing strings by ref you pass the address of the header. When passing by value you pass the address of the first character (making it a c string if you tack a null on the end).

Excel VBA Shapes TextFrame Characters Text Charset

I insert textbox to my Excel 2013 document and put some text
正体字/繁体字
with UTF-8 symbols
In textbox its looks ok but when I trying to msgbox it with command
MsgBox ActiveSheet.Shapes("Textbox 1").TextFrame.Characters.Text
I get something like
???/???
So how to set UTF_8 charset to get normally this text in msgbox or into variable?
You can create something that looks like a MsgBox and functions like a MsgBox, but can better handle UniCode:
Public Declare Function MessageBoxU Lib "user32" Alias "MessageBoxW" _
(ByVal hwnd As Long, _
ByVal lpText As Long, _
ByVal lpCaption As Long, _
ByVal wType As Long) As Long
Sub MsgBoxSubstitute()
Dim s As String
s = ChrW(8451)
MessageBoxU 0, StrPtr(s), StrPtr("MsgBox Substitute"), 0
End Sub
Using the Windows API. Note it has a nice built-in mechanism to dismiss the message.
The only workaround is to create a form and display your message in a label. I think labels are UTF-8 enabled.

Copy from MS Word document to a web page input box

In an already open word document select all text
copy selected text to clipboard
check default browser open at correct web address
if not open default browser at web address "http://thisaddress.com"
give focus to browser
paste clipboard text into input box called "input1"
or some other way to get MSword document contents to a web page input?
Currently the workflow involves a secretary logging in to the website, then filling out a web form, switching to their open MS Word document, selecting all, copying the WP document, then back to the web form and pasting into an input box, then hitting submit. What I want to do ideally have a button in MS word which opens the browser to the correct web page then copies and pastes the document into the correct input box on the page (in fact it will be the only textarea form field).
The MS Word VBA code is:
Option Explicit
Enum W32_Window_State
Show_Normal = 1
Show_Minimized = 2
Show_Maximized = 3
Show_Min_No_Active = 7
Show_Default = 10
End Enum
Private Declare Function ShellExecute Lib "shell32.dll" _
Alias "ShellExecuteA" (ByVal hWnd As Long, _
ByVal lpOperation As String, ByVal lpFile As String, _
ByVal lpParameters As String, ByVal lpDirectory As String, _
ByVal nShowCmd As Long) As Long
Function OpenURL(URL As String, WindowState As W32_Window_State) As Boolean
' Opens passed URL with default application, or Error Code (<32) upon error
Dim lngHWnd As Long
Dim lngReturn As Long
lngReturn = ShellExecute(lngHWnd, "open", URL, vbNullString, _
vbNullString, WindowState)
OpenURL = (lngReturn > 32)
End Function
Sub TestMacro()
Application.ActiveDocument.Select
Selection.Copy
OpenURL "http://localhost:8500/index.cfm?wordContent=" & Selection, W32_Window_State.Show_Maximized
End Sub
and in the coldfusion handling form
<html>
<head>
</head>
<body>
<form id="form1">
<Textarea ID="txtArea" rows=6><cfoutput>#url.wordContent#</cfoutput></textarea>
</form>
</body>
</html>
Just would like to work out how to not open a new browser window if one is already open.
In case you can modify the web-application, you may do the following:
MS-Word: Copy content to clipboard.
MS-Word: Open Url as "http://thisaddress.com/SomePage?pasteClipboard=true"
SomePage: if query-string param pasteClipboard == true, then add a javascript function to get the clipboard data into your form field.
Update:
In your macro you simply call Selection.Copy, and to open the URL using default browser check this link http://www.experts-exchange.com/Programming/Languages/Visual_Basic/Q_23225744.html
Using the code from the previous link, I made a test macro as :
Sub TestMacro()
Application.ActiveDocument.Select
Selection.Copy
OpenURL "http://thisaddress.com/SomePage?pasteClipboard=true", W32_Window_State.Show_Maximized
End Sub
I hope this was helpful.
Update 2:
Just use W32_Window_State.Show_Default, Here is the full macro:
Option Explicit
Enum W32_Window_State
Show_Normal = 1
Show_Minimized = 2
Show_Maximized = 3
Show_Min_No_Active = 7
Show_Default = 10
End Enum
Private Declare Function ShellExecute Lib "shell32.dll" _
Alias "ShellExecuteA" (ByVal hWnd As Long, _
ByVal lpOperation As String, ByVal lpFile As String, _
ByVal lpParameters As String, ByVal lpDirectory As String, _
ByVal nShowCmd As Long) As Long
Function OpenURL(URL As String, WindowState As W32_Window_State) As Boolean
' Opens passed URL with default application, or Error Code (<32) upon error
Dim lngHWnd As Long
Dim lngReturn As Long
lngReturn = ShellExecute(lngHWnd, "open", URL, vbNullString, _
vbNullString, WindowState)
OpenURL = (lngReturn > 32)
End Function
Sub TestMacro()
Application.ActiveDocument.Select
Selection.Copy
OpenURL "http://thisaddress.com/SomePage?pasteClipboard=true", W32_Window_State.Show_Default
End Sub
Another option is to look into controlling Internet Explorer from inside Word using a control.
Here is an example.
Note, this will only work with IE (unless there are dll versions of Firefox etc.)

IFDEF equivalent in VBA

I have code that needs to run on both Excel 2003 and Excel 2007, and there are a few spots where changes in the versions cause the code to halt. I tried separating these lines out with If-Else statements, but the code won't compile on either because it doesn't recognize the code used for the other. Is there any way I could tell one version to ignore a block of code, similar to a C or C++-style #ifdef, in VBA?
This is a good starting point, but it won't work with the version of Excel that its running on, since that can only be figured out at run-time, not compile time.
If you need to branch your code based on information only discoverable at run time you might consider late binding as a solution. There are two ways you can sneak around version problems.
The first way can be used if you need to Access a property or method that only exists in certain versions, you can use CallByName. The advantage of call by name is that it allows you to preserve early binding (and intellisense) for your objects as much as possible.
To give an example, Excel 2007 has a new TintAndShade property. If you wanted to change the color of a range, and for Excel 2007 also ensure TintAndShade was set to 0 you would run into trouble because your code won't compile in Excel 2003 which does not have TintAndShade as a property of the range object. If you access the property that you know is not in all versions using CallByName, you code will compile in all versions fine, but only run in the versions you specify. See below:
Sub Test()
ColorRange Selection, Excel.Application.version, 6
End Sub
Sub ColorRange(rng As Excel.Range, version As Double, ParamArray args() As Variant)
With rng.Interior
.colorIndex = 6
.Pattern = xlSolid
If version >= 12# Then
'Because the property name is stored in a string this will still compile.
'And it will only get called if the correct version is in use.
CallByName rng.Interior, "TintAndShade", VbLet, 0
End If
End With
End Sub
The second way is for classes that have to be instantiated via "New" and don't even exist in old versions. You won't run into this problem with Excel, but I will give a quickie demo so you can see what I mean:
Imagine that you wanted to do File IO, and for some bizarre reason not all of the computers had the Microsoft Scripting Runtime on them. But for some equally bizarre reason you wanted to make sure it was used whenever it was available. If set a reference to it and use early binding in your code, the code won't compile on systems that don't have the file. So you use late binding instead:
Public Sub test()
Dim strMyString As String
Dim strMyPath As String
strMyPath = "C:\Test\Junk.txt"
strMyString = "Foo"
If LenB(Dir("C:\Windows\System32\scrrun.dll")) Then
WriteString strMyPath, strMyString
Else
WriteStringNative strMyPath, strMyString
End If
End Sub
Public Sub WriteString(ByVal path As String, ByVal value As String)
Dim fso As Object '<-Use generic object
'This is late binding:
Set fso = CreateObject("Scripting.FileSystemObject")
fso.CreateTextFile(path, True, False).Write value
End Sub
Public Sub WriteStringNative(ByVal path As String, ByVal value As String)
Dim lngFileNum As Long
lngFileNum = FreeFile
If LenB(Dir(path)) Then Kill path
Open path For Binary Access Write Lock Read Write As #lngFileNum
Put #lngFileNum, , value
Close #lngFileNum
End Sub
There is a comprehensive list of all Adds and Changes to Excel Object Model since 2003:
http://msdn.microsoft.com/en-us/library/bb149069.aspx
For changes between 1997 and 2000 go here:
http://msdn.microsoft.com/en-us/library/aa140068(office.10).aspx
Yes it is possible to do conditional compilation in Excel VBA. Below is a brief resource and some example code:
Conditional Compilation
#If Win32 Then
' Profile String functions:
Private Declare Function WritePrivateProfileString Lib "KERNEL32" Alias "WritePrivateProfileStringA" (ByVal lpApplicationName As String, ByVal lpKeyName As Any, ByVal lpString As Any, ByVal lpFileName As String) As Long
Private Declare Function GetPrivateProfileString Lib "KERNEL32" Alias "GetPrivateProfileStringA" (ByVal lpApplicationName As Any, ByVal lpKeyName As Any, ByVal lpDefault As Any, ByVal lpReturnedString As String, ByVal nSize As Long, ByVal lpFileName As String) As Long
#Else
' Profile String functions:
Private Declare Function WritePrivateProfileString Lib "Kernel" (ByVal lpApplicationName As String, ByVal lpKeyName As Any, ByVal lpString As Any, ByVal lpFileName As String) As Integer
Private Declare Function GetPrivateProfileString Lib "Kernel" (ByVal lpApplicationName As String, ByVal lpKeyName As Any, ByVal lpDefault As Any, ByVal lpReturnedString As String, ByVal nSize As Integer, ByVal lpFileName As String) As Integer
#End If
Can you post the offending lines of code?
If it is a constant like vbYes or xlFileFormat or whatever, use the corresponding numeric value.
Show me what you got, I'll see if I can refactor it.
Bill