Vba excel цвет текста в msgbox

 

DOR

Пользователь

Сообщений: 178
Регистрация: 01.01.1970

есть такое сообщение:  
MsgBox «Расчет тарифа не возможен, т.к. поле <<СРОК СТРАХОВАНИЯ>> не заполненно», Title:=»Внимание!!!»  

  как <<СРОК СТРАХОВАНИЯ>> выделить жирным шрифтом и красным цветом?

 

MsgBox «все пропало шеф, » & Format(«все пропало!», «>»)  

  Похоже, это все, что доступно для строк :О(

 

ikki

Пользователь

Сообщений: 9709
Регистрация: 22.12.2012

в стандартном MsgBox нельзя.  
рисуйте UserForm и раскрашивайте TextBox’ы как угодно.  
можно даже подпрыгивающих и машущих флажками человечков добавить.

фрилансер Excel, VBA — контакты в профиле
«Совершенствоваться не обязательно. Выживание — дело добровольное.» Э.Деминг

 

DOR

Пользователь

Сообщений: 178
Регистрация: 01.01.1970

машущие флажками человечки это канечно забавно, но лишнее. можете на примере показать как разукрасить label или принципеально TextBox? Слусл такой, если поле пустое и пытаешься сохранить, то выдает ошибку, то что в <<   >> нужно заменить на жирный шрифт и красный цвет.

 

насчет цвета не знаю, а жирный шрифт можно так:  
делаем 3 поля  
1. слово «поле»  
2. слово «СТРАХОВАТЕЛЬ»  
3. фрза «не заполнено»  
Для поля 2 изменяем свойства шрифта на жирный

 

DOR

Пользователь

Сообщений: 178
Регистрация: 01.01.1970

текст ошибки будет меняться, соответственно это не подходит.

 

Юрий М

Модератор

Сообщений: 60575
Регистрация: 14.09.2012

Контакты см. в профиле

Просто в свойствах Label в строке Font укажите «жирный» (можно и размер шрифта ещё), а в строке Fore Color — выбрать нужный цвет.

 

Юрий М

Модератор

Сообщений: 60575
Регистрация: 14.09.2012

Контакты см. в профиле

Прочитал невнимательно — Вам нужно ЧАСТЬ строки. Тогда, как сказали выше — из трёх Label, А если фрагмент, который нужно красить, будет меняться, то используйте переменную.

 

DOR

Пользователь

Сообщений: 178
Регистрация: 01.01.1970

Это было бы приемлемо, если текст сообщения был примерно одинаковый, текс бокса 1 может содержать одно слово, а может и целую строку. например:  
поле <<страхователь>> не заполнено..  
Вы не можете использовать данныю программу, так как <<выбранное ТС не соответствует перечню>>…

 

ну можно по разному извратиться.  
не обязательно же в одну строку все писать.  
поле  
СТРАХОВАТЕЛЬ  
не заполнено!  

  Так ведь тоже можно. И поле под «переменное значение» сделать с запасом по ширине.

 

DOR

Пользователь

Сообщений: 178
Регистрация: 01.01.1970

извратиться то можно, но не нужно, нужно чтобы все было красиво, а не топориком рублено. придеться видать оставить капсом. хоть это и не очень…

 

ran

Пользователь

Сообщений: 7091
Регистрация: 21.12.2012

Вставьте это и попробуйте нажать кнопку.  

  Private Sub TextBox1_Exit(ByVal Cancel As MSForms.ReturnBoolean)  
If Me.TextBox1.Value = «» Then  
MsgBox «Поле <<СТРАХОВАТЕЛЬ>> не заполненно»  
Me.TextBox1.Value = «#########»  
Me.TextBox1.BackColor = RGB(255, 0, 0)  
   With TextBox1  
       .SelStart = 0  
       .SelLength = Len(Me.ActiveControl.Text)  
   End With  
Cancel = True  
End If  
End Sub

 

Тут надо использовать Rich Textbox Control, пример тут:

http://vbbook.ru/book/82/

 

DOR

Пользователь

Сообщений: 178
Регистрация: 01.01.1970

#14

21.03.2011 22:27:23

Опять же изменение цвета и размера происходит не на кусок текста, а на весь бокс. Или я может что не понял.

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

  • Home
  • VBForums
  • Visual Basic
  • Visual Basic 6 and Earlier
  • How to change the Font and Text color in MsgBox(«….»)

  1. Sep 12th, 2005, 10:20 PM


    #1

    anthonyn71 is offline

    Thread Starter


    Junior Member


    How to change the Font and Text color in MsgBox(«….»)

    Hi
    How can I change the Font and Text color in MsgBox(«…»)
    ex: if I have MsgBox(«Hello World»), how can I make «Hello World» font 14 and red text.

    Thanks


  2. Sep 12th, 2005, 10:49 PM


    #2

    Re: How to change the Font and Text color in MsgBox(«….»)

    VB/Office Guru� (AKA: Gangsta Yoda)
    I dont answer coding questions via PM. Please post a thread in the appropriate forum. Microsoft MVP 2006-2011
    Office Development FAQ (C#, VB.NET, VB 6, VBA)
    Senior Jedi Software Engineer MCP (VB 6 & .NET), BSEE, CET
    If a post has helped you then Please Rate it!
    Reps & Rating PostsVS.NET on Vista Multiple .NET Framework Versions Office Primary Interop AssembliesVB/Office Guru� Word SpellChecker�.NETVB/Office Guru� Word SpellChecker� VB6VB.NET Attributes Ex.Outlook Global Address ListAPI Viewer utility.NET API Viewer Utility
    System: Intel i7 6850K, Geforce GTX1060, Samsung M.2 1 TB & SATA 500 GB, 32 GBs DDR4 3300 Quad Channel RAM, 2 Viewsonic 24″ LCDs, Windows 10, Office 2016, VS 2019, VB6 SP6


  3. Sep 12th, 2005, 10:52 PM


    #3

    Re: How to change the Font and Text color in MsgBox(«….»)

    You have to make up a little form that has a textbox, and the buttons that you want on it. Then, instead of calling msgbox, use CALL FrmMSGBOX.
    If you show it modally, then you will have to click on an Exit Button (that has Unload Me in it) to return to the main form.

    VB Code:

    1. Option Explicit

    2. Private Sub Command1_Click()

    3.  Call ShowMsg("this is a test")

    4. End Sub

    5. Sub ShowMsg(txt As String)

    6.   Form2.Text1.ForeColor = vbRed

    7.   Form2.Text1 = txt

    8.   Form2.Show vbModal, Me

    9. End Sub


  4. Sep 12th, 2005, 10:54 PM


    #4

    Re: How to change the Font and Text color in MsgBox(«….»)

    In order to make it look like the standard msgbox you should use a Label instead of the suggested textbox since the textbox will allow for the input of text by the user and will not have anywhere close to the look your after.

    VB/Office Guru� (AKA: Gangsta Yoda)
    I dont answer coding questions via PM. Please post a thread in the appropriate forum. Microsoft MVP 2006-2011
    Office Development FAQ (C#, VB.NET, VB 6, VBA)
    Senior Jedi Software Engineer MCP (VB 6 & .NET), BSEE, CET
    If a post has helped you then Please Rate it!
    Reps & Rating PostsVS.NET on Vista Multiple .NET Framework Versions Office Primary Interop AssembliesVB/Office Guru� Word SpellChecker�.NETVB/Office Guru� Word SpellChecker� VB6VB.NET Attributes Ex.Outlook Global Address ListAPI Viewer utility.NET API Viewer Utility
    System: Intel i7 6850K, Geforce GTX1060, Samsung M.2 1 TB & SATA 500 GB, 32 GBs DDR4 3300 Quad Channel RAM, 2 Viewsonic 24″ LCDs, Windows 10, Office 2016, VS 2019, VB6 SP6


  5. Sep 12th, 2005, 11:14 PM


    #5

    Re: How to change the Font and Text color in MsgBox(«….»)

    Ok. That makes sense. Not sure if he could have figured that out. Thanks for checking it out.


  6. Sep 12th, 2005, 11:15 PM


    #6

    Re: How to change the Font and Text color in MsgBox(«….»)

    VB/Office Guru� (AKA: Gangsta Yoda)
    I dont answer coding questions via PM. Please post a thread in the appropriate forum. Microsoft MVP 2006-2011
    Office Development FAQ (C#, VB.NET, VB 6, VBA)
    Senior Jedi Software Engineer MCP (VB 6 & .NET), BSEE, CET
    If a post has helped you then Please Rate it!
    Reps & Rating PostsVS.NET on Vista Multiple .NET Framework Versions Office Primary Interop AssembliesVB/Office Guru� Word SpellChecker�.NETVB/Office Guru� Word SpellChecker� VB6VB.NET Attributes Ex.Outlook Global Address ListAPI Viewer utility.NET API Viewer Utility
    System: Intel i7 6850K, Geforce GTX1060, Samsung M.2 1 TB & SATA 500 GB, 32 GBs DDR4 3300 Quad Channel RAM, 2 Viewsonic 24″ LCDs, Windows 10, Office 2016, VS 2019, VB6 SP6


  7. Sep 13th, 2005, 12:18 AM


    #7

    anthonyn71 is offline

    Thread Starter


    Junior Member


    Re: How to change the Font and Text color in MsgBox(«….»)

    Thank you very much. I will try. Hope it gives a better look


  • Home
  • VBForums
  • Visual Basic
  • Visual Basic 6 and Earlier
  • How to change the Font and Text color in MsgBox(«….»)


Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  
  • BB code is On
  • Smilies are On
  • [IMG] code is On
  • [VIDEO] code is On
  • HTML code is Off

Forum Rules


Click Here to Expand Forum to Full Width

Вопрос:

Я хочу изменить цвет шрифта из 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

Я надеюсь, что то, что я запросил, возможно.

Лучший ответ:

Как предлагает Ральф, было бы лучше отобразить ваше сообщение в UserForm где у вас будет легкий контроль над текстовыми характеристиками.

Тем не менее, можно изменить цвет текста MessageBox, используя API цвета системы. Поскольку 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
  • Remove From My Forums
  • Question

  • dear all,

    good greeting

     i have my private code in userform vba : 

     If IsDate(Me.DTPicker3) Then

            
            If CDate(Me.DTPicker3) <= Date + 30 Or Empty Then
                MsgBox «alert» & TextBox5
                Me.TextBox5.BackColor = vbRed

                
                End If

    i want the content of textbox5 which will be appear in msg box (in bold line and red color)

    how can i made it ?

    regards………..

    • Edited by

      Monday, April 23, 2018 12:46 PM

Answers

  • Hi,

    I’m afraid MsgBox (Excel VBA) has such features. 
    If you want change size, color, or family of font, you need to use UserForm.  

    Regards,


    Ashidacchi — http://hokusosha.com/

    • Marked as answer by
      TAREK SHARAF
      Tuesday, April 24, 2018 6:06 AM

  • Hello TAREK SHARAF,

    To show the content of textbox in msgbox, you could use

    MsgBox "alert " & Me.TextBox5.Text

    However, as far as I know, msgbox does not support showing the content in bold and red color. I would also suggest you custom a userform to replace msgbox for showing the content.

    By the way, what’s the state of the below thread? If it is resolved, please mark helpful reply to close the thread. If not, please follow up to let us know your current state.

    regarding creat code to make bold border for unempty rows in excel sheet 

    Best Regards,

    Terry


    MSDN Community Support
    Please remember to click «Mark as Answer» the responses that resolved your issue, and to click «Unmark as Answer» if not. This can be beneficial to other community members reading this thread. If you have any compliments or complaints to
    MSDN Support, feel free to contact MSDNFSF@microsoft.com.

    • Marked as answer by
      TAREK SHARAF
      Tuesday, April 24, 2018 6:06 AM

Понравилась статья? Поделить с друзьями:
  • Vba excel функция процедура for
  • Vba excel хорошие книги
  • Vba excel функция поиска в строке
  • Vba excel функция ячейка
  • Vba filed в word