VBA更改MsgBox中的文本颜色

时间:2016-09-09 09:50:31

标签: vba excel-vba excel

我想更改MsgBox的字体颜色

要理解我想要的东西,我选择了这个例子:

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

'我想在"Correct"

中出现的MsgBox文字为绿色

' "Incorrect" MsgBox

中显示为红色

我希望我所要求的是可能的。

1 个答案:

答案 0 :(得分:7)

正如拉尔夫建议的那样,最好在UserForm中显示您的信息,以便轻松控制文字特征。

但是,可以使用系统颜色API更改MessageBox文本的颜色。由于MessageBox是一个Window,你可以改变它的颜色参数(不仅仅是文本,还有其他各种颜色参数)。

您需要确保之后立即重置原始值,否则所有窗口都将以修改后的颜色显示。

以下代码将自动检测32位和64位系统,并且同样可以正常工作:

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