- 1 year ago
VBA Code using Windows API for colorising Textbox selection
To colorize the selected text in a TextBox using VBA and the Windows API, you can utilize the SendMessage
function from the user32
library. Here's an example code snippet that demonstrates this:
vbaOption Explicit
Private Declare Function SendMessage Lib "user32" Alias "SendMessageA" ( _
ByVal hWnd As Long, _
ByVal wMsg As Long, _
ByVal wParam As Long, _
ByVal lParam As Long) As Long
Private Const EM_SETCHARFORMAT As Long = &H444
Private Const CFM_COLOR As Long = &H40000000
Sub ColorizeSelectedText()
Dim hWnd As Long
Dim result As Long
Dim cf As CHARFORMAT2
' Replace TextBox1 with the name of your TextBox control
hWnd = TextBox1.hWnd
' Set the desired color value (RGB)
cf.crTextColor = RGB(255, 0, 0) ' Red color
' Set the necessary structure fields
cf.cbSize = LenB(cf)
cf.dwMask = CFM_COLOR
' Call SendMessage to apply the formatting to the selected text
result = SendMessage(hWnd, EM_SETCHARFORMAT, SCF_SELECTION, VarPtr(cf))
End Sub
This code snippet declares the necessary Windows API function SendMessage
and the required constants. It then defines the CHARFORMAT2
structure, which is used to specify the text formatting attributes, including the color. The ColorizeSelectedText
subroutine sets the desired color (in this case, red) and calls SendMessage
with the EM_SETCHARFORMAT
message to apply the color formatting to the selected text in the TextBox.
Make sure to replace TextBox1
with the actual name of your TextBox control.
Please note that this code snippet uses the Windows API and may require additional error handling or adjustments based on your specific use case.