Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

VBA Change the text color in MsgBox

Tags:

excel

vba

I want to change the font color from MsgBox

To understand what I want, I chose this exemple:

Dim a As Integer
Dim b As Integer
Dim c As Integer
Dim results As String


a = InputBox("Enter your first value:")
b = InputBox("Enter your second value:")
c = InputBox("Enter your third value:")

d = a - b + c

If d = 0 Then
    results = "Correct"
    MsgBox "Your results is: " & results 
Else
    results = "Incorrect"
    MsgBox " Your Results is: " & results 
End If

The "Correct" text I want to be in green when it appears in MsgBox; the "Incorrect" text I want to be in red when it appears in MsgBox

I hope what I have requested is possible.

like image 322
BOB Avatar asked Sep 09 '16 09:09

BOB


1 Answers

As Ralph suggests, it'd be better to display your message in a UserForm where you'd have easy control over the text characteristics.

However, it is possible to change the colour of your MessageBox text, using the system color API's. As the MessageBox is a Window, you can alter the colour parameters of it (not just text, but various others too).

You'd want to ensure that you reset the original values immediately afterwards of course otherwise all of your windows will display in the modified colours.

The below code will automatically detect 32-bit and 64-bit systems and should work on both equally well:

Option Explicit

#If Win64 Then
    Private Declare PtrSafe Function GetSysColor Lib "user32" _
        (ByVal nIndex As Long) As Long
    Private Declare PtrSafe Function SetSysColors Lib "user32" _
        (ByVal nChanges As Long, lpSysColor As Long, lpColorValues As Long) As Long
#Else
    Private Declare Function GetSysColor Lib "user32" _
        (ByVal nIndex As Long) As Long
    Private Declare Function SetSysColors Lib "user32" _
        (ByVal nChanges As Long, lpSysColor As Long, lpColorValues As Long) As Long
#End If

Private Const COLOR_WINDOWTEXT As Long = 8
Private Const CHANGE_INDEX As Long = 1

Public Sub RunMe()
   Dim defaultColour As Long

   'Store the default system colour
   defaultColour = GetSysColor(COLOR_WINDOWTEXT)

   'Set system colour to red
   SetSysColors CHANGE_INDEX, COLOR_WINDOWTEXT, vbRed
   MsgBox "Incorrect", , "Your result is..."

   'Set system colour to green
   SetSysColors CHANGE_INDEX, COLOR_WINDOWTEXT, vbGreen
   MsgBox "Correct", , "Your result is..."

   'Restore default value
   SetSysColors CHANGE_INDEX, COLOR_WINDOWTEXT, defaultColour

End Sub
like image 111
Ambie Avatar answered Oct 26 '22 12:10

Ambie