Command button in word

«Excel» (Word) VBA кнопки.

Кнопки в Эксель

Кнопки в Эксель

Наверняка Вам доводилось встречать файлы «Excel» (Word) с размещенными на листах различными кнопками, по нажатию на которые происходит запуск макроса или иные действия.

Хотите узнать, как размещать кнопки на листах Excel(Word)? Тогда читайте статью дальше.

Рассмотрим 2 типа кнопок:

Самая обычная кнопка, называемая CommandButton- эта кнопка нажимается кликом и запускает какое-либо действие, записанное за ней.

Вторая кнопка называется ToggleButton и является выключателем или переключателем. Она может не только запускать действия, но и сама может нести в себе информацию – обладать двумя значениями: False и true, что соответствует ее состоянию нажата или отжата.

CommandButton выглядит так:

CommandButton

CommandButton

ToggleButton  выглядит так:

ToggleButton

ToggleButton

Процесс добавления кнопок на лист Excel (Word):

  1. Если у Вас в ленте не включена панель «Разработчик», ее нужно включить следующим образом:
    • Кликнуть по ленте правой кнопкой мыши и в выпадающем контекстном меню выбрать пункт «Настройка ленты…»
      Настройка ленты
      Настройка ленты
    • В появившемся окне на вкладке «Настроить ленту» установить флажок («галочку») напротив пункта «Разработчик»
      Настройка ленты. Разработчик
      Настройка ленты. Разработчик
    • Нажать кнопку «Ок»
  2. Когда на панели появилась вкладка разработчик, перейдите на нее и нажмите кнопку «Режим конструктора».
    Режим конструктора Excel
    Режим конструктора Excel
  3. При включённом режиме конструктора становиться активной кнопка с инструментами. Кликнув по кнопке с инструментами можно выбрать понравившейса Вам активный элемент: CommandButton или ToggleButton .
    Инструменты в режиме конструктора
    Инструменты в режиме конструктора
  4. Когда элемент выбран, удерживая нажатой левую кнопку мыши, выделите область на листе, в которую Вы хотите поместить этот элемент.
  5. Кнопка появиться в указанной области.

В режиме конструктора свойства кнопки можно менять и перемещать ее по листу. Вне режима конструктора кнопка просто выполняет свою функцию – нажимается.

Внимание: Если У вас не получается выделить кнопку на листе Excel, включите режим конструктора.

Основные свойства кнопок:

CommandButton:

BackColor – цвет фона кнопки.

Caption – Надпись на кнопке.

Enabled – состояние кнопки включена или отключена (активна или неактивна).

Font – шрифт надписи на кнопке.

ForeColor – Цвет надписи на кнопке.

Height  — высота кнопки.

Width – ширина кнопки.

Picture – изображение на поверхности кнопки.

WordWrap – перенос текста кнопки.

ToggleButton:

Свойства практически те же что и у CommandButton, добавляются параметры:

Value – это значение кнопки False и true, нажата или отжата.

TripleState – включает или отключает тройное нажатие (три состояния переключателя)

Word VBA add command buttons through code

Add CommandButton to Word Document using VBA (through AddOLEControl)

Here is one of the ways to add a command button on a Word document using Word VBA

Sub Macro_Add_Button()

Dim oCtl

Dim oCmd

Set oCtl = ActiveDocument.InlineShapes.AddOLEControl(ClassType:=»Forms.CommandButton.1″)

Set oCmd = oCtl.OLEFormat.Object

oCmd.Caption = «Click Me…»

End Sub

StumbleUpon

Related Posts Plugin for WordPress, Blogger...

  1. Jun 1st, 2022, 08:22 AM


    #1

    JonJRiches is offline

    Thread Starter


    New Member


    Exclamation Programing a Command Button in Word

    I have come here in hope………..

    I used to have a document in Lotus Notes that had a table with a «Press When Complete Button» in the last cell of row in the table.
    Once clicked, the Users Name, Date and Time would replace the button in the table. (All part of a audit trail)

    Is there anyone in here that can assist me it transferring this to Word.

    I have got as far as creating the button, I now need to program it — bit with next to NO VB experience, I am stuck.

    I have added a doc with shots of said button.

    Thanks in advance………. Jon


  2. Jun 1st, 2022, 05:50 PM


    #2

    Re: Programing a Command Button in Word

    How to create a Button in Word:

    https://docs.microsoft.com/en-us/pre…button-in-word

    Get User Name (assuming that this is the user name you are looking for):

    https://docs.microsoft.com/en-us/off…ation.username

    Get Date:

    https://docs.microsoft.com/en-us/off…/date-function

    https://docs.microsoft.com/en-us/off…insertdatetime

    Get Time:

    https://docs.microsoft.com/en-us/off…/time-function

    Sample Code:

    Code:

    Option Explicit
    
    Sub Test()
    
        'Add a command button to a new document
        Dim doc As Word.Document
        Dim shp As Word.InlineShape
        Set doc = Documents.Add
        
        Set shp = doc.Content.InlineShapes.AddOLEControl(ClassType:="Forms.CommandButton.1")
        shp.OLEFormat.Object.Caption = "Press When Complete"
        
        'Add a procedure for the click event of the inlineshape
        '**Note: The click event resides in the This Document module
        Dim sCode As String
        sCode = "Private Sub " & shp.OLEFormat.Object.Name & "_Click()" & vbCrLf & _
                "   MsgBox ""You Clicked the CommandButton""" & vbCrLf & _
                "End Sub"
        doc.VBProject.VBComponents("ThisDocument").CodeModule.AddFromString sCode
    
    End Sub
    
    
    Sub Button1_Click()
    
        '
        ' Button1_Click Macro
        '
        '
        Dim strUserName As String, strDate As String, strTime As String
        
        strUserName = Application.UserName
        strDate = Date
        strTime = Time
        MsgBox "User: " & strUserName & ", Date: " & strDate & ", Time: " & strTime, , "Button Clicked"
    
    End Sub


  1. 10-17-2021, 04:24 AM


    #1

    Command button in word

    Hi guys I was wondering if anyone could assist with adding a command button in word to select key pages and open in in a separate document I don�t need this to save just populate the pre determined pages in a new word document

    I have several documents I use at work, that are a combination of multiple documents it is lot easier to change one document then multiple documents.

    is a command button possible in this instance?

    thanks for your help in advance


  2. 10-20-2021, 06:13 AM


    #2

    First, the Word object model does not understand the concept of a page. It understands logical structures of paragraphs, words, and sections, but not pages. Word Doesn’t Know What a Page Is , Moving/Reorganizing Pages in Microsoft Word

    If your document is organized using the Built-In heading styles, or section breaks, to delineate pages you may be able to do something.

    Second, rather than a command button, I would use a regular macro and attach it to QAT button(s). Command buttons will not work on a Mac.


  3. 11-03-2021, 11:06 PM


    #3

    hi thanks for the reply

    yes the the document has built in headings which are the start of each individual section that I would like to save.

    Would you know were I could start looking to find a way to do this?


  4. 11-09-2021, 09:50 AM


    #4

    More information on what you are starting with and where you want to end up would be needed. I would recommend saving samples of your start and end documents on OneDrive or DropBox and posting a link here.


Is it possible to insert a button into a word document and call as macro on click of this button. Please let me know if you have any similar ideas and also the procedure to do it.

asked Feb 6, 2009 at 9:58

Vinod's user avatar

You’ll need to use VBA to do this, but it’s pretty straight-forward.

There’s an MS knowledge base article that describes exactly what you want to do.

answered Feb 6, 2009 at 10:08

ConroyP's user avatar

ConroyPConroyP

40.7k16 gold badges79 silver badges86 bronze badges

It is possible to insert a Command button (as well as some other contorl like radio button etc) in Word Document.
Click on the Toolbar and enable Visual basic. You will get all control boxes, Select the Command Button. You can wirte the code into in the VBA script. This will get executed on click of the Command Button.

answered Feb 6, 2009 at 10:08

Dheer's user avatar

DheerDheer

3,8766 gold badges34 silver badges45 bronze badges

Понравилась статья? Поделить с друзьями:
  • Comma and dot in excel
  • Comlete with one word
  • Coming up with the right word
  • Coming to god word
  • Coming into being word