VBA更改MsgBox中的文本颜色 [英] VBA Change the text color in MsgBox

查看:1382
本文介绍了VBA更改MsgBox中的文本颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想从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

我希望当MsgBox中出现的正确"文本为绿色;我想在MsgBox

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.

推荐答案

正如拉尔夫(Ralph)建议的那样,最好将消息显示在UserForm中,这样您可以轻松控制文本特征.

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

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

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.

以下代码将自动检测32位和64位系统,并且在两个系统上均能正常工作:

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

这篇关于VBA更改MsgBox中的文本颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆