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 |
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.
|
|
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 ‘значения Dim Dim wSheets lst_Sheet.Clear Worksheets(Worksheets.Count).Activate For Cells(i, Next lst_Sheet.RowSource End |
Подсчитывается |
Приложение 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 |
||
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 |
||
Label |
Элемент для |
Name |
watch |
Caption |
(пустая строка) |
||
Font |
Жирное начертание, |
||
TextBox |
Поле для ввода |
Name |
sec |
ToggleButton |
Установка |
Name |
left_but |
Рисунок на |
Picture |
Из |
|
Высота кнопки |
Height |
29,5 |
|
Ширина кнопки |
Width |
29,5 |
|
ToggleButton |
Установка |
Name |
right_but |
Рисунок на |
Picture |
Из |
|
Высота кнопки |
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
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.
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.
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.
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.
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