Word msgbox да нет

In this Article

  • VBA MsgBox Function
  • VBA YesNo Message Box
  • VBA Message Box Options
  • Syntax of MsgBox Function
  • Customize Message Box Title and Prompt
    • MessageBox LineBreaks
  • MsgBox Icons
    • MsgBox Icons – Information
    • MsgBox Icons – Critical
    • MsgBox Icons – Question
    • MsgBox Icons – Exclamation
  • MsgBox Variables
    • OK Message Box – vbOKOnly
    • OK Cancel Message Box – vbOKCancel
    • Yes No Message Box – vbYesNo
    • Yes No Cancel Message Box – vbYesNoCancel
    • Abort Retry Ignore Message Box – vbAbortRetryIgnore
    • Retry Cancel Message Box – vbRetryCancel
  • VBA MessageBox Examples
    • Message Box Confirmation Before Running Macro
    • Yes / No Message Box – Exit Sub
  • VBA Message Box in Access VBA

This tutorial will cover how to use the VBA MsgBox Function to display messageboxes to users (including the YesNo Messagebox). You might also be interested in our article on InputBoxes.

VBA MsgBox Function

In VBA, it’s easy to display a simple MsgBox:

MsgBox "This is a Message Box"

vba messagebox

However you can do a lot more than display a simple OK message box. Let’s quickly look at complicated example before we dive into specifics…

VBA YesNo Message Box

Below we will create a message box with:

  • A title “Message Box Title” and prompt “Text”
  • A question mark icon
  • Yes / No options instead of a simple “OK”
  • Default button = ‘No’
Dim answer As Integer

answer = MsgBox("Text", vbQuestion + vbYesNo + vbDefaultButton2, "Message Box Title")

vba yesno messagebox

The messagebox will return vbYes or vbNo depending on the user’s choice. You can then then perform different actions based on the choice:

If answer = vbYes Then
  MsgBox "Yes"
Else
  MsgBox "No"
End If

In the next section we will show you all of the options available to you when creating message boxes. Then we will introduce you to the syntax of the MsgBox Function and finally go over other message box examples.

VBA Message Box Options

Take a look at the image below. Here you will see (almost) all of the options available to you when creating message boxes. Take notice of the icons and the different buttons.

vba write messagebox code

This is a screenshot of the “MessageBox Builder” from our Premium VBA Add-in: AutoMacro. The MessageBox Builder allows you to quickly design your desired messagebox and insert the code into your code module. It also contains many other code builders, an extensive VBA code library, and an assortment of coding tools. It’s a must-have for any VBA developer.

Syntax of MsgBox Function

MsgBox( prompt [, buttons ] [, title ] [, helpfile, context ] )

prompt (Required) – This is the primary message box text.

buttons – Choose which buttons to display. If omitted, ‘OKonly’. Here you can also specify what icon to show and the default button.

title – The title at the top of the message box. If omitted, the name of the current application is displayed (ex. Microsoft Excel).

helpfile – Specify help file that can be accessed when user clicks on the ‘Help’ button. If specified, then you must also add context (below)

context – Numeric expression representing the Help context number assigned to the appropriate Help topic.

You can probably ignore the helpfile and context arguments. I’ve never seen them used.

Customize Message Box Title and Prompt

The MsgBox function allows you to customize the title and prompt messages like so:

Msgbox "Prompt",,"Title"

Another example:

Sub MsgBoxPromptTitle()
  MsgBox "Step 1 Complete. Click OK to run step 2.",, "Step 1 of 5"
End Sub

vba messagebox okonly

Important! You must remember to surround your text with quotations.

MessageBox LineBreaks

You can also add line breaks to your message box prompts with ‘vbNewLine’.

Sub MsgBoxPromptTitle_NewLine()
  MsgBox "Step 1 Complete." & vbNewLine & "Click OK to Run Step 2.", , "Step 1 of 5"
End Sub

vba messagebox insert line

Notice we use the & symbol to join text together. You can learn more about using & with text and other options for inserting linebreaks in our article on joining text.

VBA Coding Made Easy

Stop searching for VBA code online. Learn more about AutoMacro — A VBA Code Builder that allows beginners to code procedures from scratch with minimal coding knowledge and with many time-saving features for all users!

automacro

Learn More

MsgBox Icons

VBA gives you the ability to add one of four pre-built icons to your message boxes:

Icon Constant Icon
vbInformation vba information msgbox icon
vbCritical vba critical msgbox icon
vbQuestion vba question msgbox icon
vbExclamation vba exclamation msgbox icon

The Icon constant should be placed within the button argument:

Sub MsgBoxQuestionIcon()
  MsgBox "Question Example", vbQuestion
End Sub

This will generate the default ‘OK’ message box with the Question icon:

vba msgbox icon

Notice how when you type, the VBA Editor will show you the options available to you:

vba msgbox syntax

This is helpful because you don’t need to remember the exact syntax or names of icons or buttons.

Now we will demo each message box icon:

MsgBox Icons – Information

Sub MsgBoxInformationIcon()
  MsgBox "Information Example", vbInformation
End Sub

vba msgbox information

MsgBox Icons – Critical

Sub MsgBoxCriticalIcon()
  MsgBox "Critical Example", vbCritical
End Sub

vba critical message box

VBA Programming | Code Generator does work for you!

MsgBox Icons – Question

Sub MsgBoxQuestionIcon()
  MsgBox "Question Example", vbQuestion
End Sub

vba msgbox icon

MsgBox Icons – Exclamation

Sub MsgBoxExclamationIcon()
  MsgBox "Exclamation Example", vbExclamation
End Sub

msgbox exclamation icon

Below we will talk about generating message boxes with different button layouts. If you do choose a different message box type, you will need to append the icon type after the buttons using a “+”:

Sub MsgBoxQuestionIcon()
  MsgBox "Do you want to continue?", vbOKCancel + vbQuestion
End Sub

vba messagebox question

MsgBox Variables

So far we have worked primarily with the default ‘OK’ message box. The OK message box only has one option: Pressing ‘OK’ allows the code to continue.  However, you can also specify other button groupings: OK / Cancel, Yes / No, etc.

In which case you will want to perform different actions based on which button is pressed.  Let’s look at an example.

Here is the message box we will generate:

vba yes no msgbox

This is the entire code (we will break it down next):

Sub MsgBoxVariable()

Dim answer As Integer
answer = MsgBox("Do you want to Continue?", vbQuestion + vbYesNo)

  If answer = vbYes Then
    MsgBox "Yes"
  Else
    MsgBox "No"
  End If

End Sub

First we assign the messagebox output to an integer variable.

Dim answer As Integer

answer = MsgBox("Do you want to Continue?", vbQuestion + vbYesNo)

Next we use an If-Else to determine what to do based on which button is pressed:

If answer = vbYes Then
  MsgBox "Yes"
Else
  MsgBox "No"
End If

The MsgBox function returns an integer value (between 1-7) so we define the variable as an integer type.  However, instead of referring to the integer number, you can refer to a constant (ex. vbOK, vbCancel, etc.).  Look at this table to see all of the options:

Button Constant Value
OK vbOK 1
Cancel vbCancel 2
Abort vbAbort 3
Retry vbRetry 4
Ignore vbIgnore 5
Yes vbYes 6
No vbNo 7

Now we will demo each button grouping:

OK Message Box – vbOKOnly

messagebox okonly

This is the standard VBA messagebox.

Sub MsgBox_OKOnly()

Dim answer As Integer
answer = MsgBox("OKOnly Example", vbOKOnly)

End Sub

OK Cancel Message Box – vbOKCancel

messagebox okcancel

Sub MsgBox_OKCancel()

Dim answer As Integer
answer = MsgBox("OK Cancel Example", vbOKCancel)

  If answer = vbOK Then
    MsgBox "OK"
  Else
    MsgBox "Cancel"
  End If

End Sub

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

Yes No Message Box – vbYesNo

messagebox yes no

Sub MsgBox_YesNo()

Dim answer As Integer
answer = MsgBox("Yes No Example", vbYesNo)

  If answer = vbYes Then
    MsgBox "Yes"
  Else
    MsgBox "No"
  End If

End Sub

Yes No Cancel Message Box – vbYesNoCancel

messagebox yes no cancel

Sub MsgBox_YesNoCancel()

Dim answer As Integer
answer = MsgBox("Yes No Cancel Example", vbYesNoCancel)

  If answer = vbYes Then
    MsgBox "Yes"
  ElseIf answer = vbNo Then
    MsgBox "No"
  Else
    MsgBox "Cancel"
  End If

End Sub

Abort Retry Ignore Message Box – vbAbortRetryIgnore

messagebox abort retry ignore

Sub MsgBox_AbortRetryIgnore()

Dim answer As Integer
answer = MsgBox("Abort Retry Ignore Example", vbAbortRetryIgnore)

  If answer = vbAbort Then
    MsgBox "Abort"
  ElseIf answer = vbRetry Then
    MsgBox "Retry"
  Else
    MsgBox "Ignore"
  End If

End Sub

Retry Cancel Message Box – vbRetryCancel

messagebox retry cancel

Sub MsgBox_RetryCancel()

Dim answer As Integer
answer = MsgBox("Retry Cancel Example", vbRetryCancel)

  If answer = vbRetry Then
    MsgBox "Retry"
  Else
    MsgBox "Cancel"
  End If

End Sub

AutoMacro | Ultimate VBA Add-in | Click for Free Trial!

VBA MessageBox Examples

Message Box Confirmation Before Running Macro

This code will display a Yes No Message box before calling a macro. If Yes is clicked the macro is called, if No is clicked, the Macro does not run.

Sub Msgbox_BeforeRunning()

  Dim answer As Integer
  answer = MsgBox("Do you want to run Macro1?", vbQuestion + vbYesNo)

  If answer = vbYes Then Call Macro1

End Sub

vba confirmation box run macro

Yes / No Message Box – Exit Sub

Here we will confirm with the user whether to continue running a macro. If No is clicked, the code will exit the sub, otherwise the procedure will continue.

Sub Msgbox_BeforeRunning()

  Dim answer As Integer
  answer = MsgBox("Do you want to continue?", vbQuestion + vbYesNo)

  If answer = vbNo Then Exit Sub
  
  'Some Code

End Sub

vba yes no exit sub

VBA Message Box in Access VBA

All of the above examples work exactly the same in Access VBA as in Excel VBA.

vba yes no msgbox

Использование функции MsgBox в VBA Excel, ее синтаксис и параметры. Значения, возвращаемые функцией MsgBox. Примеры использования.

Функция MsgBox предназначена в VBA Excel для вывода сообщения в диалоговом окне, ожидания нажатия кнопки и возврата значения типа Integer, указывающего на то, какая кнопка была нажата. Для упрощения восприятия информации, в этой статье не рассматриваются параметры, связанные с контекстной справкой и модальностью диалогового окна MsgBox.

Синтаксис функции

MsgBox ( Prompt [, Buttons ] [, Title ])

Обязательным параметром функции MsgBox является Prompt, если Buttons и Title явно не указаны, используются их значения по умолчанию. Кроме того, если необязательные параметры не указаны и возвращаемое значение не присваивается переменной, сообщение не заключается в скобки:

Пример 1

Sub Test1()

MsgBox «Очень важное сообщение!»

End Sub

Параметры функции

Параметр Описание Значение
по умолчанию
Prompt* Обязательный параметр. Выражение типа String, отображаемое в диалоговом окне в виде сообщения. Разделить на строки можно с помощью константы vbNewLine. Нет
Buttons Необязательный параметр. Числовое выражение, которое представляет собой сумму значений, задающих номер и тип отображаемых кнопок, стиль используемого значка, тип кнопки по умолчанию. 0
Title Необязательный параметр. Выражение типа String, отображаемое в заголовке диалогового окна. Имя приложения**

*Максимальная длина параметра Prompt составляет примерно 1024 знака и зависит от их ширины.

**В Excel по умолчанию в заголовке MsgBox выводится надпись «Microsoft Excel».

Константы параметра «Buttons»

Тип и количество кнопок

Константа Описание Значение
vbOKOnly Отображается только кнопка OK. 0
vbOKCancel Отображаются кнопки OK и Cancel (Отмена). 1
vbAbortRetryIgnore Отображаются кнопки Abort (Прервать), Retry (Повторить) и Ignore (Пропустить). 2
vbYesNoCancel Отображаются кнопки Yes (Да), No (Нет) и Cancel (Отмена). 3
vbYesNo Отображаются кнопки Yes (Да) и No (Нет). 4
vbRetryCancel Отображаются кнопки Retry (Повторить) и Cancel (Отмена). 5

Стиль значка

Константа Описание Значение
vbCritical Отображается значок Critical — Критичное сообщение, сообщение об ошибке. 16
vbQuestion Отображается значок Question — Сообщение с вопросом. 32
vbExclamation Отображается значок Exclamation — Предупреждающее сообщение. 48
vbInformation Отображается значок Information — Информационное сообщение. 64

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

Пример 2

Sub Test2()

Dim a As Integer

a = MsgBox(«Критичное сообщение, сообщение об ошибке», 16)

a = MsgBox(«Сообщение с вопросом», 32)

a = MsgBox(«Предупреждающее сообщение», 48)

a = MsgBox(«Информационное сообщение», 64)

End Sub

Кнопка по умолчанию

Константа Описание Значение
vbDefaultButton1 По умолчанию активна первая кнопка. 0
vbDefaultButton2 По умолчанию активна вторая кнопка. 256
vbDefaultButton3 По умолчанию активна третья кнопка. 512

Возвращаемые значения

Константа Кнопка Значение
vbOK OK 1
vbCancel Отмена 2
vbAbort Прервать 3
vbRetry Повторить 4
vbIgnore Пропустить 5
vbYes Да 6
vbNo Нет 7

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

Для третьего примера зададим следующие параметры первой функции MsgBox:

  • Prompt = «Выберите кнопку!»
  • Buttons = 323 (3 (vbYesNoCancel) + 64 (vbInformation) + 256 (vbDefaultButton2))
  • Title = «Выбор кнопки»

Вторая функция MsgBox используется как простое информационное сообщение с параметрами по умолчанию.

Пример 3

Sub Test3()

Dim a As Integer

a = MsgBox(«Выберите кнопку!», 323, «Выбор кнопки»)

If a = 6 Then

MsgBox «Вы нажали кнопку: Да»

ElseIf a = 7 Then

MsgBox «Вы нажали кнопку: Нет»

Else

MsgBox «Вы нажали кнопку: Отмена»

End If

End Sub

В этом примере, в зависимости от нажатой кнопки в первом диалоговом окне, во втором сообщении выводится название нажатой кнопки. Обратите внимание, что вторая кнопка в открывшемся первом окне MsgBox выделена по умолчанию и срабатывает при нажатии клавиши «Enter».

А что будет, если первое диалоговое окно из третьего примера закрыть крестиком? Проверьте сами.

Last update: July 2020; Applicability: Office 365,2019, 2016, 2013.

Sometimes, we would like to make our Word documents more interactive and even capture some user input. Enter message and input boxes .

As the name suggests a message box is a piece of information that is displayed to the document users. Input boxes are instrumental to capture information from the user.

This post has all the information and code samples you’ll need to create fully functional documents with Visual Basic for Applications (VBA) message and input boxes for Microsoft Word.

How to add VBA code into Word?

Before we go ahead and explain how to add message and input boxes, here’s a quick refresher on how to add your custom VBA code to a Word document.

  • First off, go ahead and enable the Developer tab.
  • Now, hit the Visual Basic button from the Developer tab. This will open the Visual Basic Editor.

2018-01-17 16_02_28-

  • Highlight your Document.
  • Click Insert and then select Module.

2018-01-17 16_03_01-Microsoft Visual Basic for Applications - Document1

  • Copy the code we provide below into the Module you just created into your module.
  • Click on Save. Provide a name to your document if prompted.
  • Close the Visual Basic Editor.

Message Boxes VBA code

Syntax:

MsgBox(prompt,buttons,title,helpfile,context)

Syntax explanation:

Prompt:

Required. It is the information that can be given to the user. It should be inserted inside the double quotation mark.

Buttons:

Optional. Buttons are those kind of buttons that are given to the users information. There are various buttons available for MsgBox() and they can be found on the pictures below.

2018-01-16 14_24_13-

2018-01-16 14_24_44-

2018-01-16 14_25_13-

Title:

Optional. It is the title for the information given to the user. If not given, Microsoft word will be the default title.

Helpfile and context:

  • Optional. Helpfile will identify the Help file available in local disk which can be provided as a help in a dialog box
  • Optional. Context is numeric expression which is used to identify the help topic by the unique number.

Sample Message box code

'VBA
Sub messagebox()

'Variables assigned

Dim buttonclick As VbMsgBoxResult

'Message box to display information to user

<strong>MsgBox "Hi, Visual Basic is easy to work with", vbExclamation, "VBA"</strong>

'Message box to ask question to user with yes or no question
<strong>buttonclick = MsgBox("Do you like VBA?", vbQuestion + vbYesNo, "VBA")</strong>
If buttonclick = vbYes Then
<strong>MsgBox "Yes, they are great!", vbExclamation, "VBA"</strong>
Else
<strong>MsgBox "Why not? They are great!", vbCritical, "VBA"</strong>
End If

End Sub

Output:

2018-01-16 16_28_08-VBA

2018-01-16 16_28_26-VBA

2018-01-16 16_28_43-VBA

2018-01-16 16_29_05-VBA

Dialog and Input Boxes VBA code

Input box is a simple dialog that allows us to prompt the user for some information. Let us get acquainted with the VBA code using an example.

Syntax:

InputBox(Prompt, Title, Default, XPos, YPos, HelpFile, HelpContextId, Type)

Syntax explanation:

Prompt:

Required. It is the information that can be given to the user. It should be inserted inside the double quotation mark.

Title:

Optional. It is the title for the information given to the user. If not given, Microsoft word will be the default title.

Default:

Optional. It displays the default value inside the text box, before user types for a value. If not specified, the text box will be empty.

XPos:

Optional. It is used as the position on the X axis. From left to right

YPos:

Optional. It is used as the position on the Y axis. From top to bottom

Helpfile and HelpContext ID:

  • Optional. Helpfile will identify the Help file available in local disk which can be provided as a help in a dialog box
  • Optional. HelpContext ID is the id number for the help file.

Input box code:

'VBA
Sub macro()

'Variables assigned
Dim a As Long
Dim b As Long

'Input box to get value from user

a = InputBox("Enter a value for a", "Question 1")
b = InputBox("Enter a value for b", "Question 2")

'Answer displayed in a message box
MsgBox ("Answer is " &amp; Val(a) + Val(b))
End Sub

Output:

2018-01-16 16_30_13-Question 1

2018-01-16 16_30_30-Question 2

2018-01-16 16_30_59-Microsoft Word

ttt_xx

1 / 1 / 0

Регистрация: 28.01.2013

Сообщений: 102

1

04.01.2014, 19:31. Показов 24901. Ответов 17

Метки нет (Все метки)


Студворк — интернет-сервис помощи студентам

Доброго всем времени суток!
Пишу игрушку и не могу понять, как задать функции для кнопок которые открываются в MsgBox.
Например: при нажатии кнопки выход идет проверка условия была ли нажата кнопка сохранения, если да то игра закрывается, если нет то вылетает сообщение с тремя кнопками «да, нет, отмена». Мне необходимо чтобы при нажатии кнопки «Да» — игра закрывалась, «Нет» — закрывалось сообщение, и третью кнопку необходимо переименовать в «Сохранить и выйти» — где происходить запись результата и игра закрывается

код кнопки

VB.NET
1
2
3
4
5
6
7
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
        If l > 0 Then
            End
        ElseIf MsgBox("Вы действительно хотите выйти не сохранив результаты?", MsgBoxStyle.YesNoCancel) Then
        
        End If
    End Sub

код записи

VB.NET
1
2
3
4
5
6
7
 l = l + 1
        Dim result As StreamWriter
        Dim save As New System.IO.StreamWriter("D:1.txt", True)
        save.Write(imya)
        save.Write(" ")
        save.Write(cash & vbCrLf)
        save.Close()



0



Монфрид

1239 / 1049 / 293

Регистрация: 07.03.2012

Сообщений: 3,245

04.01.2014, 19:37

2

MsgBox это функция, которая возвращает там что-то (MsgBoxResultEnum по-моему). Вам надо проверить его

VB.NET
1
ElseIf MsgBox("Вы действительно хотите выйти не сохранив результаты?", MsgBoxStyle.YesNoCancel)= Then

равно подставьте как у меня, студия по идее вам должна предложить верный вариант автокомплитом



1



1 / 1 / 0

Регистрация: 28.01.2013

Сообщений: 102

04.01.2014, 19:48

 [ТС]

3

спасибо большое)



0



Petr_S

205 / 222 / 87

Регистрация: 21.04.2013

Сообщений: 404

04.01.2014, 21:26

4

Цитата
Сообщение от ttt_xx
Посмотреть сообщение

Пишу игрушку и не могу понять, как задать функции для кнопок которые открываются в MsgBox.

VB.NET
1
2
3
4
5
6
7
8
9
10
11
12
        Dim dr As DialogResult = MsgBox("Вопрос", _
                                        MsgBoxStyle.YesNoCancel Or MsgBoxStyle.Question, _
                                        "Заголовок")
 
        Select Case dr
            Case DialogResult.Yes
 
            Case DialogResult.No
 
            Case DialogResult.Cancel
 
        End Select

Цитата
Сообщение от ttt_xx
Посмотреть сообщение

третью кнопку необходимо переименовать в «Сохранить и выйти»

Такой возможности, по-моему, нет. Можно создать свою форму с тремя кнопками. Открывать ее CustomMsgBox.
ShowDialog(). Для получения значений в коде кнопок своей диалоговой формы писать что-то типа:

VB.NET
1
2
DialogResult = vbOK
        Me.Close()



0



Nachrichter

649 / 601 / 92

Регистрация: 19.03.2012

Сообщений: 1,128

04.01.2014, 21:41

5

VB.NET
1
2
3
4
5
6
Dim mess = MsgBox("Текст", 32 + 4, "Заголовок") 'значения цифр прилагаю
If mess = DialogResult.Yes then
  'code
Else
  'code
End if

Цитата
Сообщение от Petr_S
Посмотреть сообщение

Такой возможности, по-моему, нет.

Да, я тоже о такой не слышал…

P.S.: Изображение предоставлено пользователем emenem97.

Миниатюры

Использование MsgBox с кнопками "Да" и "Нет"
 



3



insite2012

Эксперт .NET

5484 / 4254 / 1211

Регистрация: 12.10.2013

Сообщений: 12,253

Записей в блоге: 2

04.01.2014, 22:33

6

Я думаю, если есть надобность в собственном мессадже, то можно вот так сделать.
Основная форма:

VB.NET
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
Public Class Form1
 
    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        Dim MyMsg As New MyMsgBox
        With MyMsg
            .FormBorderStyle = Windows.Forms.FormBorderStyle.FixedSingle
            .MaximizeBox = False
            .MinimizeBox = False
            .Button1.Text = "Yes"
            .Button2.Text = "No"
            .Button3.Text = "Save"
        End With
        MyMsg.ShowDialog()
        If MyMsg.Click_Data = 1 Then
            'Вариант 1
            MsgBox("Вариант действий 1")
        ElseIf MyMsg.Click_Data = 2 Then
            'Вариант 2
            MsgBox("Вариант действий 2")
        Else
            'Вариант 3
            MsgBox("Вариант действий 3")
        End If
    End Sub
End Class

Форма для своего мессаджа:

VB.NET
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
Public Class MyMsgBox
    Private MsgRes As String = Nothing
    Private Sub All_Click(sender As Object, e As System.EventArgs) Handles Button1.Click,
                                                                           Button2.Click, Button3.Click
        MsgRes = CType(sender, Button).Name
        Me.Close()
    End Sub
    Public ReadOnly Property Click_Data() As Integer
        Get
            If MsgRes = "Button1" Then
                Return 1
            ElseIf MsgRes = "Button2" Then
                Return 2
            Else
                Return 3
            End If
        End Get
    End Property
End Class

По возвращаемому свойству из формы мессаджа и прописывайте необходимые действия.



1



Petr_S

205 / 222 / 87

Регистрация: 21.04.2013

Сообщений: 404

04.01.2014, 23:02

7

Цитата
Сообщение от Nachrichter
Посмотреть сообщение

VB.NET
1
Dim mess = MsgBox("Текст", 32 + 4, "Заголовок") 'значения цифр прилагаю

Вместо «32 + 4» и других сочетаний удобнее писать vb-константы с Or.
Например, vbOKCancel Or vbExclamation выдаст запрос с двумя кнопками («ОК» и «Отмена») и значком «Восклицательный знак в желтом треугольнике».



1



649 / 601 / 92

Регистрация: 19.03.2012

Сообщений: 1,128

04.01.2014, 23:24

8

Цитата
Сообщение от Petr_S
Посмотреть сообщение

удобнее писать vb-константы с Or

О вкусах предпочитаю не спорить.



0



ttt_xx

1 / 1 / 0

Регистрация: 28.01.2013

Сообщений: 102

05.01.2014, 08:04

 [ТС]

9

Спасибр всем за помощь, сделал вот таким образом. Но тут есть вопрос: когда я нажимаю на кнопку «Нет» прога записывает результат, но не закрывается, и тут же снова вылетает такой же msgbox и тут при повторном нажатии кнопки «Нет» снова все записывается и прога закрывается, а должно закрываться после первого нажатия. И при нажатии кнопки отмена тоже самое, должна закрываться с первого клика, а не со второго, что тут не так?

Кликните здесь для просмотра всего текста

VB.NET
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
Private Sub Button4_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button4.Click
        If l > 0 Then
            End
        ElseIf MsgBox("Вы действительно хотите выйти не сохранив результаты?", MsgBoxStyle.YesNoCancel, "Выход") = MsgBoxResult.Yes Then
            End
        ElseIf MsgBox("Вы действительно хотите выйти не сохранив результаты?", MsgBoxStyle.YesNoCancel, "Выход") = MsgBoxResult.No Then
            l = l + 1
            Dim result As StreamWriter
            Dim save As New System.IO.StreamWriter("D:1.txt", True)
            save.Write(imya)
            save.Write(" ")
            save.Write(cash & vbCrLf)
            save.Close()
            End
        Else : Exit Sub
        End If
    End Sub



0



Release

Заблокирован

05.01.2014, 11:31

10

VB.NET
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
 If l > 0 Then
            End
        Else
            Dim MessageB As DialogResult = MessageBox.Show("Вы действительно хотите выйти не сохранив результаты?", "Выход", MessageBoxButtons.YesNoCancel)
            If MessageB = DialogResult.Yes Then End
            If MessageB = DialogResult.No Then
                l = l + 1
                Dim result As StreamWriter
                Dim save As New System.IO.StreamWriter("D:1.txt", True)
                save.Write(imya)
                save.Write(" ")
                save.Write(cash & vbCrLf)
                save.Close()
                End
            End If
            If MessageB = DialogResult.Cancel Then Exit Sub
        End If

Добавлено через 2 минуты

Цитата
Сообщение от ttt_xx
Посмотреть сообщение

И при нажатии кнопки отмена тоже самое, должна закрываться с первого клика, а не со второго, что тут не так?

ну так ты погляди на код внимательней. у тебя

Цитата
Сообщение от ttt_xx
Посмотреть сообщение

ElseIf MsgBox(«Вы действительно хотите выйти не сохранив результаты?», MsgBoxStyle.YesNoCancel, «Выход») = MsgBoxResult.Yes Then

и

Цитата
Сообщение от ttt_xx
Посмотреть сообщение

ElseIf MsgBox(«Вы действительно хотите выйти не сохранив результаты?», MsgBoxStyle.YesNoCancel, «Выход») = MsgBoxResult.No Then



0



1 / 1 / 0

Регистрация: 28.01.2013

Сообщений: 102

05.01.2014, 12:16

 [ТС]

11

Цитата
Сообщение от Release
Посмотреть сообщение

ну так ты погляди на код внимательней

а что тут не так? вроде все правильно.
Идет проверка какая кнопка была нажата



0



Эксперт .NET

5484 / 4254 / 1211

Регистрация: 12.10.2013

Сообщений: 12,253

Записей в блоге: 2

05.01.2014, 12:34

12

А чем Вам вариант с двумя формами не подошел? Названия кнопок ставьте какие надо, и все работает как и требовалось…



0



Release

Заблокирован

05.01.2014, 12:53

13

Цитата
Сообщение от ttt_xx
Посмотреть сообщение

Идет проверка какая кнопка была нажата

дак перед проверкой она вызывает MsgBox. По этому у вас два раза показывается сообщение.



0



831 / 639 / 101

Регистрация: 20.08.2013

Сообщений: 2,524

09.01.2014, 15:07

14

Цитата
Сообщение от ttt_xx
Посмотреть сообщение

и третью кнопку необходимо переименовать в «Сохранить и выйти»

Надо копать в сторону WinApi и нативного показа диалога. Примерно туда же, где присобачивается таймер обратного отсчёта. По крайней мере, мне так кажется. Не пробовал так делать.
Кстати, а с шириной кнопок тогда что?



0



Release

Заблокирован

09.01.2014, 15:32

15

Цитата
Сообщение от Qwertiy
Посмотреть сообщение

Надо копать в сторону WinApi и нативного показа диалога. Примерно туда же, где присобачивается таймер обратного отсчёта.

Мудрено больно, проще уж свой сделать.



0



831 / 639 / 101

Регистрация: 20.08.2013

Сообщений: 2,524

09.01.2014, 15:40

16

Цитата
Сообщение от Release
Посмотреть сообщение

Мудрено больно, проще уж свой сделать.

Мне кажется, проще оставить кнопку Отмена с естественной функциональностью



0



178 / 153 / 10

Регистрация: 08.11.2012

Сообщений: 224

09.01.2014, 17:51

17

Цитата
Сообщение от ttt_xx
Посмотреть сообщение

третью кнопку необходимо переименовать в «Сохранить и выйти»

VDialog по всем вопросам.



0



1300 / 506 / 63

Регистрация: 09.08.2012

Сообщений: 2,056

09.01.2014, 18:12

18

а я бы сделал ДВА msgbox’а. первый стандартный: «выйти? да/нет. Второй после нажатия Да (Выход) выскакивает предложение msgbox: «Сохранить? Да/Нет» . И не нужно ничего городить



0



msgbox ("Message goes here",0+16,"Title goes here")

if the user is supposed to make a decision the variable can be added like this.

variable=msgbox ("Message goes here",0+16,"Title goes here")

The numbers in the middle vary what the message box looks like.
Here is the list

0 — ok button only

1 — ok and cancel

2 — abort, retry and ignore

3 — yes no and cancel

4 — yes and no

5 — retry and cancel

TO CHANGE THE SYMBOL (RIGHT NUMBER)

16 — critical message icon

32 — warning icon

48 — warning message

64 — info message

DEFAULT BUTTON

0 = vbDefaultButton1 — First button is default

256 = vbDefaultButton2 — Second button is default

512 = vbDefaultButton3 — Third button is default

768 = vbDefaultButton4 — Fourth button is default

SYSTEM MODAL

4096 = System modal, alert will be on top of all applications

Note: There are some extra numbers. You just have to add them to the numbers already there like

msgbox("Hello World", 0+16+0+4096)

from https://www.instructables.com/id/The-Ultimate-VBS-Tutorial/

Понравилась статья? Поделить с друзьями:
  • Word move picture around
  • Word names for dogs
  • Word move one page
  • Word names for boys
  • Word motivation for life