Note: The other languages of the website are Google-translated. Back to English

Як увімкнути або вимкнути кнопку на основі значення комірки в Excel?

У цій статті я розповім про деякі методи ввімкнення або вимкнення кнопки на основі значення комірки на аркуші Excel.

Увімкніть або вимкніть дві кнопки на основі даних двох стовпців із кодом VBA

Увімкніть або вимкніть кнопку на основі двох значень комірок із кодом VBA

Увімкніть або вимкніть дві кнопки на основі даних двох стовпців із кодом VBA

Наприклад, у мене на робочому аркуші є дві командні кнопки, якщо стовпець A містить дані, button1 увімкнено, а кнопка 2 вимкнена; якщо стовпець C містить дані, кнопка 2 увімкнена, а кнопка 1 вимкнена. Для вирішення цього завдання вам може допомогти такий код VBA.

1. Клацніть правою кнопкою миші аркуш, що містить кнопки, а потім виберіть Переглянути код у контекстному меню див. знімок екрана:

2, в Microsoft Visual Basic для додатків вікно, скопіюйте та вставте наведений нижче код у порожній модуль:

Код VBA: Увімкніть або вимкніть дві кнопки на основі двох стовпців:

Private Sub Worksheet_Change(ByVal Target As Range)
    CommandButton1.Enabled = False
    CommandButton2.Enabled = False
    If Application.WorksheetFunction.CountA(Range("C:C")) > 0 Then
        CommandButton2.Enabled = True
    End If
    If Application.WorksheetFunction.CountA(Range("A:A")) > 0 Then
        CommandButton1.Enabled = True
    End If
End Sub

Note: In the above code, CommandButton1 and CommandButton2 are the buttons names, A:A and C:C are the two columns that you use to enable or disable two buttons, please change them to your need.

3. Then save and close the code window, now, you will get the following result as you need:

(1.) If type data in Column A, the button 1 is enabled and button 2 is disabled, see screenshot:

(2.) If type data in Column C, the button 2 is enabled and button 1 is disabled, see screenshot:

(3.) Both Column A and Column C have data, two buttons are all enabled, see screenshot:

(4.) Two buttons are all disabled if there is no data in Column A and Column C, see screenshot:

Enable or disable a button based on two cell values with VBA code

If you want to enable or disable a command button based on two cell values, such as, when value in A1 is greater than value in B1, the button is enable, else, the button is disable. The following VBA code also can do you a favor.

1. Right click the sheet that contain the button, and then choose View Code from the context menu, in the Microsoft Visual Basic for Applications window, please copy and paste the below code into the blank module, see screenshot:

VBA code: Enable or disable a button based on two cell values:

Private Sub Worksheet_Change(ByVal Target As Range)
    Dim TargetAdd As String
    Dim xTemp As Double
    On Error GoTo ExitSub
    TargetAdd = Target.Address
    CommandButton1.Enabled = False
    If (TargetAdd = Range("A1").Address) Or (TargetAdd = Range("B1").Address) Then
        If Range("A1") > Range("B1") Then
            CommandButton1.Enabled = True
        End If
    End If
End Sub

Note: In the above code, A1 and B1 are the cell values that you use, CommanButton1 is the button name, change them to your own.

2. Then save and close the code window, now, if the cell value in A1 is greater than B1, the button is enabled, else, if the cell value in A1 is less than B1, the button is disabled, see screenshot:

The Best Office Productivity Tools

Kutools for Excel Solves Most of Your Problems, and Increases Your Productivity by 80%

  • Reuse: Quickly insert complex formulas, charts and anything that you have used before; Encrypt Cells with password; Create Mailing List and send emails...
  • Super Formula Bar (easily edit multiple lines of text and formula); Reading Layout (easily read and edit large numbers of cells); Paste to Filtered Range...
  • Merge Cells/Rows/Columns without losing Data; Split Cells Content; Combine Duplicate Rows/Columns... Prevent Duplicate Cells; Compare Ranges...
  • Select Duplicate or Unique Rows; Select Blank Rows (all cells are empty); Super Find and Fuzzy Find in Many Workbooks; Random Select...
  • Exact Copy Multiple Cells without changing formula reference; Auto Create References to Multiple Sheets; Insert Bullets, Check Boxes and more...
  • Extract Text, Add Text, Remove by Position, Remove Space; Create and Print Paging Subtotals; Convert Between Cells Content and Comments...
  • Super Filter (save and apply filter schemes to other sheets); Advanced Sort by month/week/day, frequency and more; Special Filter by bold, italic...
  • Combine Workbooks and WorkSheets; Merge Tables based on key columns; Split Data into Multiple Sheets; Batch Convert xls, xlsx and PDF...
  • More than 300 powerful features. Supports Office / Excel 2007-2021 and 365. Supports all languages. Easy deploying in your enterprise or organization. Full features 30-day free trial. 60-day money back guarantee.
kte tab 201905

Office Tab Brings Tabbed interface to Office, and Make Your Work Much Easier

  • Enable tabbed editing and reading in Word, Excel, PowerPoint, Publisher, Access, Visio and Project.
  • Open and create multiple documents in new tabs of the same window, rather than in new windows.
  • Increases your productivity by 50%, and reduces hundreds of mouse clicks for you every day!
officetab bottom
Comments (1)
No ratings yet. Be the first to rate!
This comment was minimized by the moderator on the site
I receive a "Expected Function or variable" error when I incorporate this code - could you show the code you set up for the two buttons? May help me solve the error.
There are no comments posted here yet
Leave your comments
Posting as Guest
Rate this post:
0   Characters
Suggested Locations

Follow Us

Copyright © 2009 - | All rights reserved. Powered by ExtendOffice. | Sitemap
Microsoft and the Office logo are trademarks or registered trademarks of Microsoft Corporation in the United States and/or other countries.
Protected by Sectigo SSL