Word combobox добавить значения

RRS feed

  • Remove From My Forums
  • Question

  • Hi MSDN ,

    I Hav e A Word Document  in which i  hav placed a Combobox .. I want to Add Some items to That Combo box ,

    Can Any one please suggest me regarding  the Same !!!

    Thanks And Regards


    Satya Ranjan Biswal ….

Answers

  • Hi Satya

    Try substituting DropDownListEntries for ContentControlListEntries


    Cindy Meister, VSTO/Word MVP

    • Marked as answer by
      Satya, _S_ Sense
      Friday, December 4, 2009 9:56 AM

All replies

  • What do you mean by item?? is it lists or data??

    You can right click on combobox, choose Edit item for adding lists

    Or you can click arrow at the top of combobox,check use data bound item, then select your Data Source (it’s used for adding data from database)

  • Hi Satya

    There are a number of differnt kinds of «combo boxes» a Word document can host. Before we can answer your question, we need to know:

    1. What version of Word?
    2. What version of VSTO?
    3. What kind of Combobox? (If you don’t know, describe the exact steps you used to insert the combobox.)


    Cindy Meister, VSTO/Word MVP

  • Hi  Cindy ,

    I Am Using 2007 Word.,

    i hav Added The Combobox By Following Line Of Codes

     Dim oWord As Word.Application
     Dim oDoc As Word.Document
      oWord = CreateObject("Word.Application")
            oWord.Visible = True
            oDoc = oWord.Documents.Add
    
            oDoc.ContentControls.Add(WdContentControlType.wdContentControlText)
            oDoc.ContentControls.Add(WdContentControlType.wdContentControlComboBox)

    Now i want to Add The Items/Data to that Combobox ,
    How can i do that

    Thanks And Regards


    Satya Ranjan Biswal ….

  • is this data from database?? if yes, then what database you are using?? do you have connection string to that database??

  • Hi ,

    In Some Cases i hav hard Coded Data Like «YES» Or ‘NO» , in Some cases i hav to fetch data from Database .

    I am using Sql Server 2008 And Yes i Do hav a connection string ….

    Thanks And Regards


    Satya Ranjan Biswal ….

  • Hi Satya

    I’ll try to help you get started, but it’s important for you to realize that the VSTO forum is not the correct place for you to ask questions for your application as you’re not using the VSTO technology. You’ll find a description about what VSTO is, what the forum supports, and links to places where you can ask non-VSTO, Office-related questions in the forum’s Please Read First message.

    The combobox type of Content control has a ContentControlListEntries property, which in turn gives you access to an Add method. This method will let you populate the dropdown list for the control. You must assign a value that the user can see. Optionally, you can also assign a different «value» for the entry, and you can give an index value (for placing the entry at a specific position in the list).

    I urge you to create an object for the Content Control you’re inserting, and work with that. For example:

    Dim ccComboBox as Word.ContentControl = oDoc.ContentControls.Add(WdContentControlType.wdContentControlComboBox)
    ccComboBox.ContentControlListEntries.Add(«The text», «The value», 1)


    Cindy Meister, VSTO/Word MVP

  • hi Harrie ,

    I think u r not getting the question perfectly ,

    I am Asking about Filling the Combobox in WordDcoument,  Not A Normal Combobox.
    By d Way i know Multiple Type of Data Fetching Techniques .

    i m placing the combo nby following Code

     Dim
     oWord As
     Word.Application
    Dim oDoc As Word.Document
    oWord = CreateObject("Word.Application" )
    oWord.Visible = True
    oDoc = oWord.Documents.Add

    oDoc.ContentControls.Add(WdContentControlType.wdContentControlText)
    oDoc.ContentControls.Add(WdContentControlType.wdContentControlComboBox)


    Satya Ranjan Biswal ….

  • Hi Cindy , I pasted Code But It is showimng Error For The Following Line

    ccComboBox.ContentControlListEntries.Add(«The text», «The value», 1)
    And The Error Desc is

    ContentControlListEntries’ is not a member of ‘Microsoft.Office.Interop.Word.ContentControl’.   

    Thanks ANd Regards


    Satya Ranjan Biswal ….

  • Hi Satya

    Try substituting DropDownListEntries for ContentControlListEntries


    Cindy Meister, VSTO/Word MVP

    • Marked as answer by
      Satya, _S_ Sense
      Friday, December 4, 2009 9:56 AM

  • Try this:

    Sub SetPlaceholderText()
     
        Dim objCC As ContentControl
        
        Set objCC = Selection.ContentControls _
            .Add(wdContentControlComboBox)
        objCC.Title = "Favorite Animal"
        objCC.SetPlaceholderText _
            Text:="Please select your favorite animal "
        
        'List entries
        objCC.DropdownListEntries.Add "Cat"
        objCC.DropdownListEntries.Add "Dog"
        objCC.DropdownListEntries.Add "Horse"
        objCC.DropdownListEntries.Add "Monkey"
        objCC.DropdownListEntries.Add "Snake"
        objCC.DropdownListEntries.Add "Other"
     
    End Sub
    

    or this to fetch data from database

    Function PopulateTestComboBox(cmbName As String)
        Dim dbDatabase As Database
        Dim rst As Recordset
        Dim i As Integer
        Dim objCC As ContentControl
        
        strDBPath = "C:MyPathMyDB.mdb"
     
        Set dbDatabase = OpenDatabase(strDBPath)
        Set rst = dbDatabase.OpenRecordset("SELECT TestName FROM tbl_Tests ORDER BY TestName", dbOpenSnapshot)
        ActiveDocument.ContentControls("ComboBox11").Range.Select
        Set objCC = Selection.ContentControls _
                        .Add(wdContentControlComboBox)
     
        i = 0
        With objCC
            'Add initial blank value
            .DropdownListEntries.Add ("")
            i = i + 1
            Do Until rst.EOF
                .DropdownListEntries.Add (rst.Fields("TestName"))
                rst.MoveNext
                i = i + 1
            Loop
            'Add final value "Other"
            .DropdownListEntries.Add ("Other")
            'Set to initial blank value
            .SetPlaceholderText Text:=""
        End With
    End Function
    

  • Thanks Harrie i Did the Same ……


    Satya Ranjan Biswal ….

Элемент управления ComboBox VBA языка позволяет формировать комбинированный список. Он предоставляет возможность, как выбирать готовые значения, так и вводить собственные данные. Вообще, стоит сказать, что робота со списками требует отдельной темы по определению, так как наиболее ярким примером создания сложных и комбинированных списков является  — формирование базы данных.

Однако и тут есть один момент – большая часть возможностей языка VBA отходит на задний план. Даже продукт Microsoft Access (работа с базами данных), который в былые времена я скрупулезно изучал на уроках информатики, мне на практике ни разу не пригодился.

Поэтому, и в этой статье я не буду вникать во все премудрости компонента ComboBox.

Базовые свойства элемента управления ComboBox VBA языка:

  • ColumnCount – позволяет задать количество столбиков в списке
  • ColumnWidth – ширина столбиков
  • ColumnHeads – определяет, отображать (значение true) или не отображать (значение false) заголовки столбиков.
  • RowSource – позволяет задать диапазон для элементов списка
  • Value и Text – собственно, текущее значение, что хранится в списке.

Как и для компонента TextBox, для ComboBox главным событием является Change. Событие Change возникает при вводе данных в список.

Ладно, пора приступать к практике. Сначала мы напишем пример использования объекта языка VBA ComboBox в Excel, а потом в Word.

VBA ComboBox Excel

vba combobox excel

И так, добавьте в окно Проекта новый модуль и новую форму. Модуль назовите ComboBox, а форму – CB_Form, за имена отвечает свойство Name. В редакторе кода для модуля пропишите следующую процедуру:

Sub ComboBox()
    CB_Form.Show
End Sub

Процедура сделает форму видимой.

Теперь нужно приступить к созданию и настройке формы. Как она выглядит, вы можете просмотреть на картинке, но… для “слепого” браузера я ее опишу.

Параметры формы (UserForm): название (Caption) — работа с ComboBox в VBA, ширина – 340, высота – 190.

Параметры надписи (Label): Имя (Name) L_CB, свойство Caption оставляете пустым, ширина 324, высота 30, отступ слева и сверху равен 6.

Далее нам следует добавить четыре элемента управления vba ComboBox excel, разместите их так: по два в одну строку, имена для каждого компонента задайте такие: CB_A, CB_B, CB_C и CB_D. Я выбрал такие имена потому, что в каждом списке будет отображаться содержимое текущего листа Excel для колонок A, B, C и D.

Это важно!!! Позаботьтесь, что бы содержимое колонок A-B не было пустым и что бы количество  в них элементов не было слишком огромным, достаточно 100 записей максимум. В противном случае у вас возникнут ошибки.

Для наглядности над каждым объектом ComBox vba можете поставить надписи вида: Ячейка А, Ячейка В и так далее.

В самом низу, разместите, кнопку с именем CommandButton1 и напишите на ней “Объединить”.

Ладно, теперь в редакторе кода для форму пропишите следующие процедуры:

Private Sub CommandButton1_Click()
L_CB.Caption = CB_A.Value & " " & _
CB_B.Value & " " & _
CB_C.Value & " " & _
CB_D.Value
End Sub
 
Private Sub UserForm_Initialize()
Dim oColumn As Range
Dim oCell As Range
 
'Заполняем первый список
Set oColumn = Columns("A")
For Each oCell In oColumn.Cells
If oCell.Value <> "" Then
CB_A.AddItem oCell.Value
End If
Next
CB_A.ListIndex = 0
 
'Заполняем второй список
Set oColumn = Columns("B")
For Each oCell In oColumn.Cells
If oCell.Value <> "" Then
CB_B.AddItem oCell.Value
End If
Next
CB_B.ListIndex = 0
 
'Заполняем третий список
Set oColumn = Columns("C")
For Each oCell In oColumn.Cells
If oCell.Value <> "" Then
CB_C.AddItem oCell.Value
End If
Next
CB_C.ListIndex = 0
 
'Заполняем четвертый список
Set oColumn = Columns("D")
For Each oCell In oColumn.Cells
If oCell.Value <> "" Then
CB_D.AddItem oCell.Value
End If
Next
CB_D.ListIndex = 0
 
End Sub

Процедура CommandButton1_Click – тут происходит обработка клика по кнопке. После клика, произойдет считывание выбранных данных для каждого объекта ComboBox vba excel, далее, все четыре значения объединяются и записываются в содержимое свойства Caption объекта Надпись.

Процедура UserForm_Initialize – тут происходит заполнение списков содержимым колонок сразу после инициализации формы. Происходит выбор заданной колонки листа Excel, потом циклично идет перебор всех ее значений и их добавление (метод AddItem) в выбранный список.

VBA ComboBox Word

combobox word vba

Тут мы создадим список, состоящий из трех колонок, как он выглядит, можно посмотреть на рисунке. Не буду вникать во все премудрости, а сразу покажу код:

Private Sub UserForm_Initialize()
 
With ComboBox1
.ColumnCount = 3
.ColumnWidths = "50;50;50"
.ColumnHeads = False
.RowSource = ""
End With
 
ComboBox1.AddItem "Украина"
ComboBox1.List(0, 1) = "Киев"
ComboBox1.List(0, 2) = "Украинский"
 
ComboBox1.AddItem "Россия"
ComboBox1.Column(1, 1) = "Москва"
ComboBox1.Column(2, 1) = "руский"
 
ComboBox1.AddItem "Белоруссия"
ComboBox1.List(2, 1) = "Минск"
ComboBox1.List(2, 2) = "русский"
 
ComboBox1.ListIndex = 0
 
End Sub

Как видим, при инициализации мы сначала заполняем свойства объекта ComboBox1 в блоке with … wend: три колонки, равной длины, заголовки отсутствуют. Далее происходит ручное заполнение списка. Как видим, элемент первой колонки добавляется с помощью метода AddItem, остальные колонки заполняются как массивы с помощью метода List.

0 / 0 / 0

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

Сообщений: 3

1

15.03.2014, 06:14. Показов 9527. Ответов 4


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

Есть форма, которая создает список литературы в ворде 2010. Необходимо создать combobox, чтобы задать тип источника. Не показывает, собака, данные! Ни через additem, ни через массив. Есть userform1_activate, если добавлять код туда, тоже не отображает элементы. Помогите пожалуйста!



0



2784 / 716 / 106

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

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

15.03.2014, 11:33

2

Странно, у меня показывает. Смотри:



0



mc-black

2784 / 716 / 106

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

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

15.03.2014, 11:46

3

Visual Basic
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Option Explicit
 
Private Sub UserForm_Activate()
    ComboBox1.Clear
    ComboBox1.AddItem "Один"
    ComboBox1.AddItem "Два"
    ComboBox1.AddItem "Три"
    ComboBox1.AddItem "Четыре"
    ComboBox1.AddItem "Пять"
    ComboBox1.AddItem "Шесть"
    ComboBox1.AddItem "Семь"
    ComboBox1.AddItem "Восемь"
    ComboBox1.AddItem "Девять"
    ComboBox1.AddItem "Десять"
    ComboBox1.ListIndex = 0
End Sub

Вложения

Тип файла: zip Doc1.zip (14.6 Кб, 62 просмотров)



0



0 / 0 / 0

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

Сообщений: 3

15.03.2014, 12:45

 [ТС]

4

Добавлено через 1 минуту
Всё равно не работает!(
Куда еще кроме Activate можно запилить данные?



0



0 / 0 / 0

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

Сообщений: 1

16.06.2015, 09:35

5



0



IT_Exp

Эксперт

87844 / 49110 / 22898

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

Сообщений: 92,604

16.06.2015, 09:35

5

RRS feed

  • Remove From My Forums
  • Question

  • Hi MSDN ,

    I Hav e A Word Document  in which i  hav placed a Combobox .. I want to Add Some items to That Combo box ,

    Can Any one please suggest me regarding  the Same !!!

    Thanks And Regards


    Satya Ranjan Biswal ….

Answers

  • Hi Satya

    Try substituting DropDownListEntries for ContentControlListEntries


    Cindy Meister, VSTO/Word MVP

    • Marked as answer by
      Satya, _S_ Sense
      Friday, December 4, 2009 9:56 AM

All replies

  • What do you mean by item?? is it lists or data??

    You can right click on combobox, choose Edit item for adding lists

    Or you can click arrow at the top of combobox,check use data bound item, then select your Data Source (it’s used for adding data from database)

  • Hi Satya

    There are a number of differnt kinds of «combo boxes» a Word document can host. Before we can answer your question, we need to know:

    1. What version of Word?
    2. What version of VSTO?
    3. What kind of Combobox? (If you don’t know, describe the exact steps you used to insert the combobox.)


    Cindy Meister, VSTO/Word MVP

  • Hi  Cindy ,

    I Am Using 2007 Word.,

    i hav Added The Combobox By Following Line Of Codes

     Dim oWord As Word.Application
     Dim oDoc As Word.Document
      oWord = CreateObject("Word.Application")
            oWord.Visible = True
            oDoc = oWord.Documents.Add
    
            oDoc.ContentControls.Add(WdContentControlType.wdContentControlText)
            oDoc.ContentControls.Add(WdContentControlType.wdContentControlComboBox)

    Now i want to Add The Items/Data to that Combobox ,
    How can i do that

    Thanks And Regards


    Satya Ranjan Biswal ….

  • is this data from database?? if yes, then what database you are using?? do you have connection string to that database??

  • Hi ,

    In Some Cases i hav hard Coded Data Like «YES» Or ‘NO» , in Some cases i hav to fetch data from Database .

    I am using Sql Server 2008 And Yes i Do hav a connection string ….

    Thanks And Regards


    Satya Ranjan Biswal ….

  • Hi Satya

    I’ll try to help you get started, but it’s important for you to realize that the VSTO forum is not the correct place for you to ask questions for your application as you’re not using the VSTO technology. You’ll find a description about what VSTO is, what the forum supports, and links to places where you can ask non-VSTO, Office-related questions in the forum’s Please Read First message.

    The combobox type of Content control has a ContentControlListEntries property, which in turn gives you access to an Add method. This method will let you populate the dropdown list for the control. You must assign a value that the user can see. Optionally, you can also assign a different «value» for the entry, and you can give an index value (for placing the entry at a specific position in the list).

    I urge you to create an object for the Content Control you’re inserting, and work with that. For example:

    Dim ccComboBox as Word.ContentControl = oDoc.ContentControls.Add(WdContentControlType.wdContentControlComboBox)
    ccComboBox.ContentControlListEntries.Add(«The text», «The value», 1)


    Cindy Meister, VSTO/Word MVP

  • hi Harrie ,

    I think u r not getting the question perfectly ,

    I am Asking about Filling the Combobox in WordDcoument,  Not A Normal Combobox.
    By d Way i know Multiple Type of Data Fetching Techniques .

    i m placing the combo nby following Code

     Dim
     oWord As
     Word.Application
    Dim oDoc As Word.Document
    oWord = CreateObject("Word.Application" )
    oWord.Visible = True
    oDoc = oWord.Documents.Add

    oDoc.ContentControls.Add(WdContentControlType.wdContentControlText)
    oDoc.ContentControls.Add(WdContentControlType.wdContentControlComboBox)


    Satya Ranjan Biswal ….

  • Hi Cindy , I pasted Code But It is showimng Error For The Following Line

    ccComboBox.ContentControlListEntries.Add(«The text», «The value», 1)
    And The Error Desc is

    ContentControlListEntries’ is not a member of ‘Microsoft.Office.Interop.Word.ContentControl’.   

    Thanks ANd Regards


    Satya Ranjan Biswal ….

  • Hi Satya

    Try substituting DropDownListEntries for ContentControlListEntries


    Cindy Meister, VSTO/Word MVP

    • Marked as answer by
      Satya, _S_ Sense
      Friday, December 4, 2009 9:56 AM

  • Try this:

    Sub SetPlaceholderText()
     
        Dim objCC As ContentControl
        
        Set objCC = Selection.ContentControls _
            .Add(wdContentControlComboBox)
        objCC.Title = "Favorite Animal"
        objCC.SetPlaceholderText _
            Text:="Please select your favorite animal "
        
        'List entries
        objCC.DropdownListEntries.Add "Cat"
        objCC.DropdownListEntries.Add "Dog"
        objCC.DropdownListEntries.Add "Horse"
        objCC.DropdownListEntries.Add "Monkey"
        objCC.DropdownListEntries.Add "Snake"
        objCC.DropdownListEntries.Add "Other"
     
    End Sub
    

    or this to fetch data from database

    Function PopulateTestComboBox(cmbName As String)
        Dim dbDatabase As Database
        Dim rst As Recordset
        Dim i As Integer
        Dim objCC As ContentControl
        
        strDBPath = "C:MyPathMyDB.mdb"
     
        Set dbDatabase = OpenDatabase(strDBPath)
        Set rst = dbDatabase.OpenRecordset("SELECT TestName FROM tbl_Tests ORDER BY TestName", dbOpenSnapshot)
        ActiveDocument.ContentControls("ComboBox11").Range.Select
        Set objCC = Selection.ContentControls _
                        .Add(wdContentControlComboBox)
     
        i = 0
        With objCC
            'Add initial blank value
            .DropdownListEntries.Add ("")
            i = i + 1
            Do Until rst.EOF
                .DropdownListEntries.Add (rst.Fields("TestName"))
                rst.MoveNext
                i = i + 1
            Loop
            'Add final value "Other"
            .DropdownListEntries.Add ("Other")
            'Set to initial blank value
            .SetPlaceholderText Text:=""
        End With
    End Function
    

  • Thanks Harrie i Did the Same ……


    Satya Ranjan Biswal ….

I’m new to VBA, so I’m struggling with this for a couple of days now.

I have a combobox in Word with contacts, I also have an excel file(contacts.xls) with one column (names of the all the contacts). When I open the Word-document the Macro has to fill in the combobox with all the names from the excel file.

Is it possible to send me a working example of this for word 2007? Seems quite simple, but just can’t get this to work…

Thanks in advance!

asked Dec 13, 2012 at 14:26

Ruben Horemans's user avatar

2

If you intend on reading from an Excel file in Word you are going to have to open it. It will use code like this:

   Dim oExcel As Object
   Dim oBook As Object
   Dim oSheet As Object

   'Start a new workbook in Excel
   Set oExcel = CreateObject("Excel.Application")
   Set oBook = oExcel.Workbooks.Open("FileName.xlsx")

You will also probably want to go to Tools->References in the VB project and find whatever Excel library is on your machine (and check it of course). There are ways around this if needed, but it is easier.

You then can read the values from the workbook:

oBook.Worksheets(1).cells(1,1)

I’m not totally sure what the syntax to get it into the combo box is. Look up «combobox object members» in the vbe in word. There will be a list property, or something like that.

Sorry, I’m on a linux machine right now, so I can’t debug exact code for you.

answered Dec 14, 2012 at 7:33

Poisson Aerohead's user avatar

I have more full code for you now:

Option Explicit

Sub TestDropDownFromExcel()

    Dim counter As Long
    Dim xlApp As Excel.Application
    Dim xlBook As Workbook
    Dim oCC As ContentControl

    Set oCC = ActiveDocument.ContentControls(1)

    Set xlApp = CreateObject("Excel.Application")
    Set xlBook = xlApp.Workbooks.Open("C:PathToMyFile.xlsx")

    If xlBook Is Nothing Then
        Exit Sub
    End If

    oCC.DropdownListEntries.Clear

    For counter = 1 To 10
        oCC.DropdownListEntries.Add Text:=xlBook.Worksheets(1).Cells(counter, 1), Value:=CStr(counter)
    Next counter

    xlApp.Visible = True

    Set xlBook = Nothing
    Set xlApp = Nothing 

End Sub

Be aware that there is very little error checking going on here. Also, rather than the call to .Visible at the end, you can simply call .Close if you do not want the user to see it (for the final project, this is probably preferable. The deferencing (= Nothing) is good practice to have, but VBA cleans up automatically at the end of execution. Obviously I am assuming tyou want the first dropdown (ContentCOntrols(1)) but this may not be true.

answered Dec 14, 2012 at 15:42

Poisson Aerohead's user avatar

1

Понравилась статья? Поделить с друзьями:
  • Word combinations with say
  • Word combinations with product
  • Word combinations with price
  • Word combinations with meeting
  • Word combinations with letters