gpt4 book ai didi

excel - VBA更改MsgBox中的文本颜色

转载 作者:行者123 更新时间:2023-12-02 07:36:04 25 4
gpt4 key购买 nike

我想更改 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

当“正确”文本出现在 MsgBox 中时,我希望其显示为绿色;当“不正确”文本出现在 MsgBox

中时,我希望其显示为红色

我希望我所要求的能够实现。

最佳答案

正如 Ralph 建议的那样,最好在 UserForm 中显示消息,这样您就可以轻松控制文本特征。

但是,可以使用系统颜色 API 更改 MessageBox 文本的颜色。由于 MessageBox 是一个窗口,因此您可以更改它的颜色参数(不仅是文本,还可以更改其他各种参数)。

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

下面的代码将自动检测 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

关于excel - VBA更改MsgBox中的文本颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39408720/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com