简体   繁体   中英

VBA Change the text color in MsgBox

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM