BOB*_*BOB 5 excel vba excel-vba
我想从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
Run Code Online (Sandbox Code Playgroud)
'当"Correct"我出现时,我希望用绿色的文字MsgBox
'当"Incorrect"我出现时,我希望用红色的文字MsgBox
我希望我所要求的是可能的.
小智 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
Run Code Online (Sandbox Code Playgroud)