Перейти до основного матеріалу

Як синхронізувати розкривні списки на кількох аркушах у Excel?

Припустімо, у вас є розкривні списки на кількох робочих аркушах у книзі, які містять однакові розкривні елементи. Тепер ви хочете синхронізувати розкривні списки на робочих аркушах, щоб після вибору елемента зі спадного списку на одному аркуші розкривні списки на інших аркушах автоматично синхронізувалися з тим самим вибором. У цій статті наведено код VBA, який допоможе вирішити цю проблему.

Синхронізуйте розкривні списки на кількох аркушах за допомогою коду VBA


Синхронізуйте розкривні списки на кількох аркушах за допомогою коду VBA

Наприклад, розкривні списки знаходяться на п’яти робочих аркушах з іменами Аркуш1, Аркуш2, ..., Аркуш5, щоб синхронізувати розкривні списки в інших робочих аркушах відповідно до вибору розкривного списку на Аркуші1, застосуйте наступний код VBA, щоб виконати це.

1. Відкрийте Аркуш1, клацніть правою кнопкою миші вкладку аркуша та виберіть Переглянути код з меню правою кнопкою миші.

2 В Microsoft Visual Basic для додатків вставте наведений нижче код VBA у вікно Аркуш1 (Код) вікна.

Код VBA: Синхронізація розкривного списку на кількох аркушах

Private Sub Worksheet_Change(ByVal Target As Range)
'Updated by Extendoffice 20220815
    Dim tSheet1 As Worksheet
    Dim tRange As Range
    Dim xRangeStr As String
    On Error Resume Next
    If Target.Count > 1 Then Exit Sub
    
    xRangeStr = "A2:A11"

    Set tRange = Intersect(Target, Range(xRangeStr))
    If Not tRange Is Nothing Then
        xRangeStr = tRange.Address
        Application.EnableEvents = False
        Set tSheet1 = ActiveWorkbook.Worksheets("Sheet2")
        tSheet1.Range(xRangeStr).Value = Target.Value
        Set tSheet1 = ActiveWorkbook.Worksheets("Sheet3")
        tSheet1.Range(xRangeStr).Value = Target.Value
        Set tSheet1 = ActiveWorkbook.Worksheets("Sheet4")
        tSheet1.Range(xRangeStr).Value = Target.Value
        Set tSheet1 = ActiveWorkbook.Worksheets("Sheet5")
        tSheet1.Range(xRangeStr).Value = Target.Value
        Application.EnableEvents = True
    End If
    
End Sub

Примітки:

1) У коді A2: A11 це діапазон, що містить розкривний список. Переконайтеся, що всі розкривні списки знаходяться в одному діапазоні на різних аркушах.
2) Аркуш2, Аркуш3, Аркуш4 та Sheet5 це робочі аркуші, які містять розкривні списки, які потрібно синхронізувати на основі розкривного списку на Аркуші1;
3) Щоб додати більше аркушів у код, додайте наступні два рядки перед рядком «Application.EnableEvents = True", потім змініть назву аркуша "Sheet5” до потрібного імені.
Установіть tSheet1 = ActiveWorkbook.Worksheets("Sheet5")
tSheet1.Range(xRangeStr).Value = Target.Value

3 Натисніть кнопку інший + Q клавіші, щоб закрити Microsoft Visual Basic для додатків вікна.

Відтепер, коли ви вибираєте елемент зі спадного списку в Аркуш1, розкривні списки на вказаних робочих аркушах буде автоматично синхронізовано, щоб мати однаковий вибір. Перегляньте наведену нижче демонстрацію.


Демонстрація: синхронізація розкривних списків на кількох аркушах у Excel

Найкращі інструменти продуктивності офісу

🤖 Kutools AI Aide: Революціонізуйте аналіз даних на основі: Інтелектуальне виконання   |  Згенерувати код  |  Створення спеціальних формул  |  Аналізуйте дані та створюйте діаграми  |  Викликати функції Kutools...
Популярні функції: Знайдіть, виділіть або визначте дублікати   |  Видалити порожні рядки   |  Об’єднайте стовпці або клітинки без втрати даних   |   Раунд без Формули ...
Супер пошук: VLookup за кількома критеріями    Багатозначний VLookup  |   VLookup на кількох аркушах   |   Нечіткий пошук ....
Розширений розкривний список: Швидке створення випадаючого списку   |  Залежний спадний список   |  Виберіть розкривний список, що вибирається ....
Менеджер колонок: Додайте конкретну кількість стовпців  |  Перемістити стовпці  |  Перемкнути статус видимості прихованих стовпців  |  Порівняйте діапазони та стовпці ...
Особливості: Фокус сітки   |  Перегляд дизайну   |   Велика панель формул    Диспетчер робочих книг і аркушів   |  Бібліотека ресурсів (автотекст)   |  Вибір дати   |  Об’єднайте робочі аркуші   |  Шифрування/розшифрування клітинок    Надсилайте листи за списком   |  Супер фільтр   |   Спеціальний фільтр (фільтр жирний/курсив/закреслений...) ...
Топ-15 наборів інструментів12 текст Tools (додати текст, Видалити символи, ...)   |   50 + Графік типи (діаграма Ганта, ...)   |   40+ Практичний Формули (Розрахуйте вік на основі дня народження, ...)   |   19 вставка Tools (Вставте QR-код, Вставити зображення зі шляху, ...)   |   12 Перетворення Tools (Числа до слів, Валютна конверсія, ...)   |   7 Злиття та розділення Tools (Розширені комбіновані ряди, Розділені клітини, ...)   |   ... і більше

Покращуйте свої навички Excel за допомогою Kutools для Excel і відчуйте ефективність, як ніколи раніше. Kutools для Excel пропонує понад 300 додаткових функцій для підвищення продуктивності та економії часу.  Натисніть тут, щоб отримати функцію, яка вам найбільше потрібна...

Опис


Вкладка Office Передає інтерфейс із вкладками в Office і значно полегшує вашу роботу

  • Увімкніть редагування та читання на вкладках у Word, Excel, PowerPoint, Publisher, Access, Visio та Project.
  • Відкривайте та створюйте кілька документів на нових вкладках того самого вікна, а не в нових вікнах.
  • Збільшує вашу продуктивність на 50% та зменшує сотні клацань миші для вас щодня!
Comments (7)
No ratings yet. Be the first to rate!
This comment was minimized by the moderator on the site
Hi,

thanks for the code, it worked well. Is it possible to adapt the code so that i restructure all sheets as main sheet and can change all other drop down menus from sheet 1 and at the same time from sheet 2, sheet 3, ...? I don't know anything about VBA, but I could use your code successfully for sheet1 as main sheet. Now need the possibility to synchronize the drop down menus across all sheets.

Thanks!
This comment was minimized by the moderator on the site
Hi,

I appreciate your content a lot. I am struggling to find the code to write to have drop-downs synchronized in excel. My synchronization needs to be a lot more complex and I have been trying to use ChatGPT to help write it but a robot can only do so much. I figured I would reach out and see if you could provide some direction or advise if I am making progress since I am becoming more and more frustrated. I need drop downs in Sheet 3 to correspond with drop-downs on Sheet 1 and Sheet 2. The drop-downs in Sheet 3 are all in Column A and each cell in Column A corresponds to a different dropdown on either Sheet 1 or Sheet 2. Those dropdowns have conditional formatting to highlight certain cells when an item is selected from the list. The options are "Complete" (Highlights Green), "Not Satisfied" (Highlights Orange), and "Delinquent" (Highlights red). It is probably confusing to read but I use excel to track loan payments and I have very detailed instructions I am trying to code in excel. For example, I am trying to write the code to tell excel to do the following:

1. I need cell A7 on ACORE Cash Mgmt Sheet (Sheet 3) to align with the dropdown and the conditional formatting in cell C427 on the 8th payment sheet (Sheet 1)
2. I need A8 on ACORE Cash Mgmt Sheet to align with the dropdown and the conditional formatting in C231 on the 8th payment sheet
3. I need A9 on ACORE Cash Mgmt Sheet to align with the dropdown and the conditional formatting in C133 on the 8th payment sheet
4. I need A10 on ACORE Cash Mgmt Sheet to align with the dropdown and the conditional formatting in C270 on the 8th payment sheet
5. I need A11 on ACORE Cash Mgmt Sheet to align with the dropdown and the conditional formatting in C351 on the 8th payment sheet
6. I need A12 on ACORE Cash Mgmt Sheet to align with the dropdown and the conditional formatting in C3 on the 8th payment sheet
7. I need A13 on ACORE Cash Mgmt Sheet to align with the dropdown and the conditional formatting in C39 on the 8th payment sheet
8. I need A14 on ACORE Cash Mgmt Sheet to align with the dropdown and the conditional formatting in C116 on the 8th payment sheet
9. I need A15 on ACORE Cash Mgmt Sheet to align with the dropdown and the conditional formatting in C144 on the 8th payment sheet
10. I need A16 on ACORE Cash Mgmt Sheet to align with the dropdown and the conditional formatting in C64 on the 8th payment sheet
11. I need A17 on ACORE Cash Mgmt Sheet to align with the dropdown and the conditional formatting in C158 on the 8th payment sheet
12. I need A18 on ACORE Cash Mgmt Sheet to align with the dropdown and the conditional formatting in C199 on the 8th payment sheet
13. I need A19 on ACORE Cash Mgmt Sheet to align with the dropdown and the conditional formatting in C103 on the 8th payment sheet
14. I need A20 on ACORE Cash Mgmt Sheet to align with the dropdown and the conditional formatting in C380 on the 8th payment sheet
15. I need A21 on ACORE Cash Mgmt Sheet to align with the dropdown and the conditional formatting in C81 on the 8th payment sheet
16. I need A22 on ACORE Cash Mgmt Sheet to align with the dropdown and the conditional formatting in C169 on the 8th payment sheet
17. I need A23 on ACORE Cash Mgmt Sheet to align with the dropdown and the conditional formatting in C418 on the 8th payment sheet
18. I need A24 on ACORE Cash Mgmt Sheet to align with the dropdown and the conditional formatting in C301 on the 8th payment sheet
19. I need A25 on ACORE Cash Mgmt Sheet to align with the dropdown and the conditional formatting in C95 on the 8th payment sheet
20. I need A26 on ACORE Cash Mgmt Sheet to align with the dropdown and the conditional formatting in C407 on the 8th payment sheet
21. I need A27 on ACORE Cash Mgmt Sheet to align with the dropdown and the conditional formatting in C15 on the 8th payment sheet
22. I need A28 on ACORE Cash Mgmt Sheet to align with the dropdown and the conditional formatting in C340 on the 8th payment sheet
23. I need A29 on ACORE Cash Mgmt Sheet to align with the dropdown and the conditional formatting in C211 on the 8th payment sheet
24. I need A30 on ACORE Cash Mgmt Sheet to align with the dropdown and the conditional formatting in C52 on the 8th payment sheet


This is the code that got me the closet to do what I wanted...however, I could not get it to work exactly how I wanted and it would only be for the first instructions and not include everything else:

Private Sub Worksheet_Change(ByVal Target As Range)
Dim SourceSheet As Worksheet
Dim DestSheet As Worksheet
Dim SourceCell As Range
Dim DestCell As Range
Dim FormattingRange As Range

' Set the source and destination sheets
Set SourceSheet = ThisWorkbook.Sheets("ACORE Cash Mgmt")
Set DestSheet = ThisWorkbook.Sheets("8th Payment")

' Set the source and destination cells
Set SourceCell = SourceSheet.Range("A7")
Set DestCell = DestSheet.Range("C427")

' Set the formatting range
Set FormattingRange = DestCell

' Check if the change was in the source cell
If Not Intersect(Target, SourceCell) Is Nothing Then
' Copy the value from the source cell to the destination cell
DestCell.Value = SourceCell.Value

' Apply conditional formatting based on the value
Select Case SourceCell.Value
Case "Complete"
FormattingRange.Interior.Color = RGB(146, 208, 80) ' Green
Case "Not Satisfied"
FormattingRange.Interior.Color = RGB(255, 192, 0) ' Orange
Case "Delinquent"
FormattingRange.Interior.Color = RGB(255, 0, 0) ' Red
Case Else
FormattingRange.Interior.ColorIndex = xlNone ' Clear formatting
End Select
End If
End Sub


Are you able to provide any expertise? I hope this all makes some sense considering it reads quite poorly.

Thank you in advance,

Sam
This comment was minimized by the moderator on the site
Crystal,

Thank you so much for your response, this worked! How could I modify the code to add another cell in the same sheet 6, B3 that also needed to be synchronized with B8 in sheet 7? I have attempted to modify it below, however it ends up putting the contents of B3 on sheet 6 in B7 on sheet 7 instead of B8.


Private Sub Worksheet_Change(ByVal Target As Range)
'Updated by Extendoffice 20221025
Dim tSheet1 As Worksheet
Dim tRange1 As Range
Dim tRange2 As Range
Dim xRangeStr1 As String
Dim xRangeStr2 As String
On Error Resume Next
If Target.Count > 1 Then Exit Sub

xRangeStr1 = "B2"
xRangeStr2 = "B3"

Set tRange1 = Range("B7")
If Not tRange1 Is Nothing Then
xRangeStr1 = tRange1.Address
Application.EnableEvents = False
Set tSheet1 = ActiveWorkbook.Worksheets("Sheet7")
tSheet1.Range(xRangeStr1).Value = Target.Value
Application.EnableEvents = True
End If

Set tRange2 = Range("B8")
If Not tRange2 Is Nothing Then
xRangeStr2 = tRange2.Address
Application.EnableEvents = False
Set tSheet1 = ActiveWorkbook.Worksheets("Sheet7")
tSheet1.Range(xRangeStr2).Value = Target.Value
Application.EnableEvents = True
End If

End Sub
This comment was minimized by the moderator on the site
Hi,

How can I do this if my dropdowns are in different ranges? To elaborate, I have one drop down in sheet 7 that is in cell B7 and the same dropdown on sheet 6 in cell B2.

Thank you,
Elaine
This comment was minimized by the moderator on the site
Hi E,
The following VBA code can help.
Here I take Sheet6 as the main worksheet, right click the sheet tab, select View Code from the right-click menu, then copy the following code in the Sheet6 (Code) window. When you select any item from the drop-down list in B2 of Sheet6, the drop-down list in B7 of Sheet7 will be cynchronized to have the same selected item.

Private Sub Worksheet_Change(ByVal Target As Range)
'Updated by Extendoffice 20221025
    Dim tSheet1 As Worksheet
    Dim tRange As Range
    Dim xRangeStr As String
    On Error Resume Next
    If Target.Count > 1 Then Exit Sub
    
    xRangeStr = "B2"
    
    Set tRange = Range("B7")
    If Not tRange Is Nothing Then
        xRangeStr = tRange.Address
        Application.EnableEvents = False
        Set tSheet1 = ActiveWorkbook.Worksheets("Sheet7")
        tSheet1.Range(xRangeStr).Value = Target.Value
        Application.EnableEvents = True
    End If
    
End Sub
This comment was minimized by the moderator on the site
Hi Crystal,

Thank you so much for your response, your code worked! I have a cell right under b2 and b7, b3 and b8 respectively that need to have the same function. I tried to rewrite your code as shown below, however this did not work. It caused b7 instead of b8 to change when I changed b3. Might you be able to identify what I am doing wrong?

Thank you so much!

Private Sub Worksheet_Change(ByVal Target As Range)
'Updated by Extendoffice 20221025
    Dim tSheet1 As Worksheet
    Dim tRange1 As Range
    Dime tRange2 As Range
    Dim xRangeStr1 As String
    Dim xRangeStr2 As String
    On Error Resume Next
    If Target.Count > 1 Then Exit Sub
    
    xRangeStr1 = "B2"
    xRangeStr2="B3"
    
    Set tRange1 = Range("B7")
    If Not tRange1 Is Nothing Then
        xRangeStr1 = tRange1.Address
        Application.EnableEvents = False
        Set tSheet1 = ActiveWorkbook.Worksheets("Sheet7")
        tSheet1.Range(xRangeStr1).Value = Target.Value
        Application.EnableEvents = True
    End If
    
    Set tRange2 = Range("B8")
    If Not tRange2 Is Nothing Then
        xRangeStr2 = tRange2.Address
        Application.EnableEvents = False
        Set tSheet1 = ActiveWorkbook.Worksheets("Sheet7")
        tSheet1.Range(xRangeStr2).Value = Target.Value
        Application.EnableEvents = True
    End If

End Sub
This comment was minimized by the moderator on the site
Hi E,
There is something wrong with the VBA code I replied to you above.
For the new question you mentioned, please try the following code.

Private Sub Worksheet_Change(ByVal Target As Range)
'Updated by Extendoffice 20221031
    
    Dim xBool1 As Boolean
    Dim xBool2 As Boolean
    Dim xRgStr As String
    Dim tRange As Range
    
    xRangeStr1 = "B2"
    xRangeStr2 = "B3"
    xRgStr = ""
    
    On Error Resume Next
    If Target.Count > 1 Then Exit Sub
    xBool1 = Intersect(Target, Range(xRangeStr1)) Is Nothing
    xBool2 = Intersect(Target, Range(xRangeStr2)) Is Nothing
    
    If xBool1 And xBool2 Then Exit Sub
    
    xRgStr = Target.Address(False, False, xlA1, False, False)
    
    If Target.Address(False, False, xlA1, False, False) = xRangeStr1 Then
        xRgStr = "b7"
    ElseIf Target.Address(False, False, xlA1, False, False) = xRangeStr2 Then
        xRgStr = "b8"
    End If
    If xRgStr = "" Then Exit Sub
    
    Application.EnableEvents = False
    Set tSheet1 = ActiveWorkbook.Worksheets("Sheet7")
    tSheet1.Range(xRgStr).Value = Target.Value
    Application.EnableEvents = True

End Sub
There are no comments posted here yet
Please leave your comments in English
Posting as Guest
×
Rate this post:
0   Characters
Suggested Locations