Excel vba source control

Access for Microsoft 365 Access 2021 Access 2019 Access 2016 Access 2013 Access 2010 Access 2007 More…Less

Applies to

BoundObjectFrame Object

ListBox Object

CheckBox Object

OptionButton Object

ComboBox Object

OptionGroup Object

CustomControl Object

TextBox Object

GroupLevel Object

ToggleButton Object

You can use the ControlSource property to specify what data appears in a control. You can display and edit data bound to a field in a table, query, or SQL statement. You can also display the result of an expression. Read/write String.

expressio
n.ControlSource

expression Required. An expression that returns one of the objects in the Applies To list.

Setting

The ControlSource property uses the following settings.

Setting

Description

A field name

The control is bound to a field in a table, query, or SQL statement. Data from the field is displayed in the control. Changes to the data inside the control change the corresponding data in the field. (To make the control read-only, set the Locked property to Yes.) If you click a control bound to a field that has a Hyperlink data type, you jump to the destination specified in the hyperlink address.

An expression

The control displays data generated by an expression. This data can be changed by the user but isn’t saved in the database.

You can set the ControlSource property for a control by using the control’s property sheet, a macro, or Visual Basic for Applications (VBA) code.

You can also set the ControlSource property for a text box by typing a field name or expression directly in the text box in form Design view or report Design view.

For a report, you can set this property by selecting a field or typing an expression in the Field/Expression pop-up window in the Group, Sort and Total pane.

In VBA, use a string expression to set the value of this property.

Remarks

For a report group level, the ControlSource property determines the field or expression to group on.

Note: The ControlSource property doesn’t apply to check box, option button, or toggle button controls in an option group. It applies only to the option group itself.

For reports, the ControlSource property applies only to report group levels.

Forms and reports act as «windows» into your database. You specify the primary source of data for a form or report by setting its RecordSource property to a table, query, or SQL statement. You can then set the ControlSource property to a field in the source of data or to an expression. If the ControlSource property setting is an expression, the value displayed is read-only and not saved in the database. For example, you can use the following settings.

Sam
ple setting

Description

LastName

For a control, data from the LastName field is displayed in the control. For a report group level, Microsoft Office Access 2007 groups the data on last name.

=Date( ) + 7

For a control, this expression displays a date seven days from today in the control.

=DatePart(«q»,ShippedDate)

For a control, this expression displays the quarter of the shipped date. For a report group level, Access groups the data on the quarter of the shipped date.

Example

The following example sets the ControlSource property for a text box named AddressPart to a field named City:

Forms!Customers!AddressPart.ControlSource = «City»

The next example sets the ControlSource property for a text box named Expected to the expression =Date() + 7.

Me!Expected.ControlSource = «=Date() + 7»

Need more help?

Want more options?

Explore subscription benefits, browse training courses, learn how to secure your device, and more.

Communities help you ask and answer questions, give feedback, and hear from experts with rich knowledge.

  • Home
  • VBForums
  • Visual Basic
  • Visual Basic 6 and Earlier
  • Setting a comboBox’s controlSource in EXCEL *RESOLVED*

  1. Feb 18th, 2004, 07:17 PM


    #1

    Daniel McCool is offline

    Thread Starter


    Lively Member

    Daniel McCool's Avatar


    Setting a comboBox’s controlSource in EXCEL *RESOLVED*

    I am doing some VBA in excel, and a comboBox on my form. How to i set the source of the combo box to a list of cells on my spreadsheet? I’m not sure how to format the value for the Combo.ControlSource. Any help? THanks.

    Last edited by Daniel McCool; Feb 19th, 2004 at 10:33 PM.

    «Some love is fire, some love is rust. But the finest, cleanest love is lust.» — James Bond


  2. Feb 18th, 2004, 07:32 PM


    #2

    In code:

    VB Code:

    1. ComboBox1.ListFillRange = "A1:A10"

    Bruce.


  3. Feb 18th, 2004, 07:34 PM


    #3

    In Design, specify the Range in the ListFillRange. Like A1:A10

    Note NO quotes if done in the IDE.


  4. Feb 18th, 2004, 08:02 PM


    #4

    Daniel McCool is offline

    Thread Starter


    Lively Member

    Daniel McCool's Avatar


    There is no such value for the combo box. I’m doing it in a form, not the spreedsheet, by the way.

    «Some love is fire, some love is rust. But the finest, cleanest love is lust.» — James Bond


  5. Feb 18th, 2004, 08:05 PM


    #5

    Sorry I saw the word VBA and assumed that your Form was in VBA too.

    No matter… watch this space.


  6. Feb 18th, 2004, 08:19 PM


    #6

    You could go at least two ways.

    1. Iterate past each Cell (by opening an instance of the .xls in VB) and using the .AddItem property, Or

    2. Load the .xls (as you would an .mdb!) using the JetEngine, so you can treat the
    data as if it were a Table, and load the Combo with its .DataSource and .DataField properties.

    Preference?

    Bruce.


  7. Feb 18th, 2004, 09:57 PM


    #7

    I have played with that option 2 of my previous post, but don’t beleive its possible with a VB ComboBox with out the use of .Additem.

    So, rolling over to Item 1 of my previous post:

    VB Code:

    1. Option Explicit

    2. 'Note: NO reference to MS Excel Object Library x.x is required in this example

    3. Private Sub Command1_Click()

    4. Dim objExcel As Object

    5. Dim lngCnt As Long

    6. Dim lngRowCount As Long

    7. On Error GoTo Err_Handler

    8.     'Craete an Instance of Excel

    9.     Set objExcel = CreateObject("Excel.Application")

    10.     'Open your Excel File

    11.     objExcel.Workbooks.Open "C:test.xls", , True   'Open Read-Only

    12.     'Show the SpreedSheet

    13.     'objExcel.Visible = True

    14.     lngRowCount = objExcel.ActiveSheet.UsedRange.Rows.Count

    15.     Combo1.Clear

    16.     For lngCnt = 1 To lngRowCount

    17.         Combo1.AddItem objExcel.Range("A" & lngCnt).Value

    18.     Next

    19.     Set objExcel = Nothing

    20. Exit Sub

    21. Err_Handler:

    22.     'quit Excel

    23.     If Not (objExcel Is Nothing) Then objExcel.Application.Quit

    24.     If Not (objExcel Is Nothing) Then Set objExcel = Nothing

    25.     MsgBox "Number: " & Err.Number & vbCrLf & _

    26.     "Description: " & Err.Description, vbOKOnly + vbCritical, "Error!"

    27. End Sub

    Bruce.


  8. Feb 19th, 2004, 01:35 AM


    #8

    Daniel McCool is offline

    Thread Starter


    Lively Member

    Daniel McCool's Avatar


    No. The comboBox IS in VBA. It’s in a VBA form that is in an Excel worksheet. What I meant is that the comboBox is on this form and not in a cell. Sorry for the confusion. If you still want to help me I’d greatly appreciate your time.

    In Excel, the comboBoxs have no .DataSource/.DataField values. Only .RowSource and .ControlSource.

    «Some love is fire, some love is rust. But the finest, cleanest love is lust.» — James Bond


  9. Feb 19th, 2004, 03:17 PM


    #9

    for a range of data, use:

    VB Code:

    1. ComboBox1.RowSource = "A1:A10"

    If you want to capture the entire used row data, then:

    VB Code:

    1. ComboBox1.RowSource = "A1:A" & ActiveSheet.UsedRange.Rows.Count

    Your right, you wont find any .DataSource etc properties

    Unfortunatly, M$ never had the forsight to make all THEIR apps standard…. now there is a nasty word (Note that Excel and Access are developed in different countires).
    ie. Excel VBA syntax even varies to Access VBA synatx, let alone syntax in Excel itself (Combo on a Form v a Combo on a SpreedSheet)!!!

    Bruce

    Last edited by Bruce Fox; Feb 19th, 2004 at 03:20 PM.


  10. Mar 31st, 2017, 05:40 PM


    #10

    MolarPigeon1385 is offline


    New Member


    Re: Setting a comboBox’s controlSource in EXCEL *RESOLVED*

    Question, I just signed up, I’m a novice and I’ve got a question that’s been bugging me for a while. I’m not a VB expert, I just play around with it, but here is my problem. I’ve created a form. On the form I’ve got a combo box. For that combobox (ComboBox1), I’ve set the «RowSource» in the properties, to a named range from one of my worksheets. Here comes the problem. I’ve set the «ControlSource» to a cell in my master worksheet; and everything works as long as the form loads when the user is on that worksheet; but if they load the form from another worksheet, then the ControlSource value populates from the active worksheet rather than the worksheet where I want it to populate. I’m sure that this is an easy fix; but I haven’t found a solution looking online.
    In the «Properties» section, I can’t manually enter the worksheet name and cell value; it keeps giving me the following error: «Could not set the ControlSource property. Invalid property value.»
    So, how do I link it to a specific worksheet and a specific cell in that worksheet?


  11. Mar 31st, 2017, 07:55 PM


    #11

    Re: Setting a comboBox’s controlSource in EXCEL *RESOLVED*

    MolarP…..first, welcome to the site…but I am not certain you are in the CORRECT forum here. It appears you MAY be using Microsoft Excel (you mentioned ‘master worksheet’). IF so, you MAY be attempting to use VBA (Visual Basic for Applications)—similar to VB6, but really a different animal. If that is true (you’re trying to do something ‘within Excel’, let us know and one of us will ask a Moderator (the Forum police) to move this thread to the proper forum.

    If indeed, you ARE using VB6 (Visual Basic 6.0), then I think I need a bit more information on what you are trying to do…maybe explain it once again, a bit differently (and slowly…I live in the south).

    And lastly, if you have a question, it is MUCH better if you start your own thread rather than dig up an old one…and this one is REAL old…13 years old!

    What I’d do if I were you, is go ahead and start a NEW Thread and restate your problem/question…AND, let us know what VB product you are using (VBA (which is integrated in MS Office products), VB6, or even a VB.NET product).

    Sammi


  • Home
  • VBForums
  • Visual Basic
  • Visual Basic 6 and Earlier
  • Setting a comboBox’s controlSource in EXCEL *RESOLVED*


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

title keywords f1_keywords ms.prod api_name ms.assetid ms.date ms.localizationpriority

ListBox.ControlSource property (Access)

vbaac10.chm11221

vbaac10.chm11221

access

Access.ListBox.ControlSource

3122f8ec-d7d6-18b2-5a68-2c175d2b0d85

02/21/2019

medium

ListBox.ControlSource property (Access)

Use the ControlSource property to specify what data appears in a control. You can display and edit data bound to a field in a table, query, or SQL statement. You can also display the result of an expression. Read/write String.

Syntax

expression.ControlSource

expression A variable that represents a ListBox object.

Remarks

The ControlSource property uses the following settings.

Setting Description
A field name The control is bound to a field in a table, query, or SQL statement. Data from the field is displayed in the control. Changes to the data inside the control change the corresponding data in the field. (To make the control read-only, set the Locked property to Yes.)

If you choose a control bound to a field that has a Hyperlink data type, you jump to the destination specified in the hyperlink address.

An expression The control displays data generated by an expression. This data can be changed by the user but isn’t saved in the database.

For reports, the ControlSource property applies only to report group levels.

Forms and reports act as «windows» into your database. You specify the primary source of data for a form or report by setting its RecordSource property to a table, query, or SQL statement. You can then set the ControlSource property to a field in the source of data or to an expression.

If the ControlSource property setting is an expression, the value displayed is read-only and not saved in the database. For example, you can use the following settings.

Sample setting Description
LastName For a control, data from the LastName field is displayed in the control. For a report group level, Microsoft Access groups the data on last name.
=Date( ) + 7 For a control, this expression displays a date seven days from today in the control.
=DatePart("q",ShippedDate) For a control, this expression displays the quarter of the shipped date. For a report group level, Access groups the data on the quarter of the shipped date.

Example

The following example sets the ControlSource property for a text box named AddressPart to a field named City.

Forms!Customers!AddressPart.ControlSource = "City"

The following example sets the ControlSource property for a text box named Expected to the expression =Date() + 7.

Me!Expected.ControlSource = "=Date() + 7"

[!includeSupport and feedback]

Связь формы с ячейками рабочего листа

Элементы
управления могут быть связаны с объектом
Range, представляющим
интервал ячеек рабочего листа.

Элемент TextBox

Свойство
ControlSource элемента
TextBox указывает на
ячейку рабочего листа, связывая этот
элемент формы с объектом Range,
таким образом, что в режиме выполнения
формы содержимое заданной ячейки
высветится в элементе TextBox
и, наоборот, текст, введенный в TextBox,
автоматически попадает в связанную с
ним ячейку.

Свойство
ControlSource задается как
ссылка на ячейку, например, B2.
В таком виде ссылка указывает на ячейку
активного рабочего листа. Для ссылки
на ячейку произвольного листа адрес
ячейки указывается после имени листа,
разделитель – восклицательный знак,
например, MySheet!B2.

Оператор
установки свойства ControlSource
объекта Inp_Box
рассмотренного выше примера может
выглядеть так: Inp_Box.ControlSource=»MySheet!B2″,
если
анализируемый текст расположен в ячейке
B2 рабочего
листа MySheet.

Элемент ListBox

Свойство
RowSource объекта
ListBox связывает
список с ячейками рабочего листа.
Интервал ячеек задается ссылкой на
адрес ячейки левого верхнего угла и
адрес ячейки нижнего правого угла,
разделенные двоеточием. Если интервал
ячеек расположен на конкретном листе,
то имя листа предшествует границам
интервала с восклицательным знаком в
качестве разделителя, например,
MySheet!A15:C43.

В событийной
процедуре инициализации формы рассмотрен
третий способ создания списка, связывающий
значения списка с ячейками рабочего
листа.

Private Sub
UserForm_Initialize()

‘значения
списка из ячеек рабочего листа

Dim
wSheets As Integer

Dim
i As Integer

wSheets
= WorkSheets.Count

lst_Sheet.Clear

Worksheets(Worksheets.Count).Activate

For
i = 1 To wSheets

Cells(i,
1) = WorkSheets(i).Name

Next
i

lst_Sheet.RowSource
= ActiveSheet.Name & «!A1:A» & wSheets

End
Sub

Подсчитывается
количество рабочих листов, список
очищается и активизируется последний
рабочий лист. Перечень имен рабочих
листов создается в последовательных
ячейках столбца A,
начиная с первой. В свойстве RowSource
устанавливается ссылка на созданный
перечень листов, связывая таким
образом элемент ListBox
формы Act_Sheet
с ячейками последнего рабочего листа.

Приложение 2

Форма имитирует
электронные часы, которые посекундно
отсчитывают время.

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

Конструирование форм

Для приложения
спроектируем две формы (см. рис. 7.15).

  • Первая форма
    (начальная) будет выполнять настройки
    пользователя. Пользователь может
    выбрать из списка цвет фона электронных
    часов. При выборе опции CountUp
    устанавливается прямой отсчет времени,
    а при выборе опции CountDown устанавливается
    обратный отсчет времени. При выборе
    любой из этих двух опций загружается
    следующая форма. Нажатие на командную
    кнопку Exit закрывает форму и завершает
    приложение.

  • Bторая форма будет
    запускать электронные часы. Пользователь
    может установить количество секунд,
    в течение которых будет высвечиваться
    время. Нажатие командной кнопки Start
    или щелчок на свободное пространство
    формы запускает электронные часы.
    Кнопки со стрелками инициируют отсчет
    времени назад (левая кнопка) или отсчет
    времени вперед (правая кнопка) без
    возвращения в основную форму. Командная
    кнопка New_select позволяет вернуться
    в основную форму и сделать новые
    настройки.

Вставьте две новые
формы, расположите на них элементы
управления и установите их свойства в
соответствии с рисунками и таблицей.


(a)

(b)

Рис. 7.15. (a) -форма для пользовательских
настроек;

(b) — форма для запуска
электронных часов

Свойства элементов
управления форм

Тип элемента

Комментарий

Свойства

Значение
свойства

Начальная
форма для настроек пользователя

UserForm

Форма

Name

el_watch_custom

Caption

Make Selection

Label

Поясняющий
текст для списка цветов

Name

Label1

Caption

Select color of
e_watch

Label

Поясняющий
текст для опции отсчета времени
вперед

Name

Label2

Caption

Count_Up

Label

Поясняющий
текст для опции отсчета времени назад

Name

Label3

Caption

Count_Down

CommandButton

Кнопка завершения
работы с формой

Name

Cmd_exit

Caption

Exit

Accelerator

E

ListBox

Список цветов

Name

theColors

Frame

Рамка для
переключателей

Name

Frame1

Caption

Indicator

OptionButton

Отсчет вперед
от текущего времени до времени
останова

Name

Count_Up

OptionButton

Отсчет назад
от времени останова до времени запуска
формы

Name

Count_Down

Вызываемая
форма
с электронными часами

UserForm

Форма

Name

ew

Caption

Electronic Watch

Label

Поясняющий
текст

Name

Label1

Caption

Enter second from 1 to
10 and click Start

Label

Элемент для
высвечивания времени

Name

watch

Caption

(пустая строка)

Font

Жирное начертание,
размер 16

TextBox

Поле для ввода
числа секунд

Name

sec

ToggleButton

Установка
порядка отсчета времени назад

Name

left_but

Рисунок на
кнопке

Picture

Из
файла
left_arrow_normal

папки
Program
FilesCommon FilesRoxio SharedTutorialGraphics

Высота кнопки

Height

29,5

Ширина кнопки

Width

29,5

ToggleButton

Установка
порядка отсчета времени вперед

Name

right_but

Рисунок на
кнопке

Picture

Из
файла
right_arrow_normal

папки
Program
FilesCommon FilesRoxio SharedTutorialGraphics

Высота кнопки

Height

29,5

Ширина кнопки

Width

29,5

CommandButton

Пуск электронных
часов

Name

cmd_Go

Caption

Start

Accelerator

S

CommandButton

Изменение
установок пользователя

Name

cmd_new_select

Caption

New_Select

Accelerator

N

Соседние файлы в предмете [НЕСОРТИРОВАННОЕ]

  • #
  • #
  • #
  • #
  • #
  • #
  • #
  • #
  • #
  • #
  • #

This tutorial explains difference among Record Source, Control Source, Row Source in Access Report and Form.

In Access Report and Form, there are three different data sources, which can be very confusing for starter.

Record Source

Record Source is a Property of  Report and Form, it is the data source that you want to appear in Report and Form. Record Source can be SQL statement, Table, Query.

Record Source can have more than one Field that actually appears in the Report or Form, therefore you can simply select the whole table instead of selecting specific Fields.

You can modify the Record Source by going to Report or Form Property > Data >Record Source, as show in the below picture

difference

In VBA, you can change Record Source using RecordSource Property

Me.RecordSource = "Select * From TableName"

If you try to change Record Source of a closed Form or Report, you must need to open it first. The below code shows how you can use VBA in Form1 (active Form) to open Form2 (closed Form)  and then change the Record Source

DoCmd.OpenForm "Form2"
Forms!Form2.RecordSource = "Select * From TableName"

Alternatively, you can simply put the RecordSource statment under Load Event of Form2.

For Access Report

DoCmd.OpenReport "Report Name", acViewPreview, "Query Name", "Criteria"

Afterwards save and close the report

DoCmd.Close acReport, "Report Name", acSaveYes

Control Source

Control includes Text Box, Combo Box, etc, anything you can find under the Design tab.

difference_01

Control Source is what data you want to display in the Control. After you have selected Record Source for the Form, you will be able to see all Field names of Record Source in Control Source. You can select a Field name in Control Source, or use an expression to make condition.

Another function for Control Source is to write value in the Table. If you set Allow Edits Property to Yes, you can modify the data  and will save the updated value in the Table.

For example, Job Table contains 3 Fields: Employee ID, Name, Department. I want the Report to use these Fields, so I choose Job Table as a Record Source of a Report. Then I want to display a Text Box showing Employee name for each record,  I need to change the Control Source of Text Box to Name.

The below picture shows the Data tab of Text Box Property.

difference_02

To change the Record Source of Control in VBA, use ControlSource Property. Below is an example of how to change Control Source of Text Box called Text19.

Me.Text19.ControlSource = "Name"

The Control Source in Combo Box has a different meaning, please refer to the below section.

Row Source

Row Source is the data source for use in List Box and Combo Box. It can be SQL, Table, or Query.

difference_03

Combo Box and List Box are basically the same, except that List Box shows multiple values at once but Combo Box only shows one value at one time.

The list of values that appears in Combo Box and List Box come from Row Source Property.

difference_04

The Control Source of Combo Box and List Box is different from that in other Controls. In other Controls, Control Source is how you want to Control (Text Box for example) to display value and save value.

Since the display value of Combo Box come from Row Source, Control Source only serves the purpose of save value.

To change Row Source in VBA, use RowSource Property. Below code shows how you can set the RowSource Property using SQL to return Distinct value to avoid duplicates.

Me.Combo17.RowSource = “SELECT DISTINCT Job.[Empl ID] FROM Job”

Click here to learn more about Combo Box

Outbound References

https://msdn.microsoft.com/en-us/library/office/ff835046.aspx?f=255&MSPPError=-2147217396

Like this post? Please share to your friends:
  • Excel vba sorting function
  • Excel vba sort function
  • Excel vba solver макрос описание параметров
  • Excel vba sheets или worksheets
  • Excel vba sheets cell