跳到主要內容

 如何在Excel中根據單元格值運行宏?

假設我的工作簿中有多個宏代碼,現在,我想基於單元格值運行這些代碼。 本文,我將討論在使用Excel的日常工作中可能遇到的幾種情況。

如果單元格值大於或小於VBA代碼中的特定值,則運行或觸發宏

如果單元格值等於帶有VBA代碼的特定文本,則運行或觸發宏


箭頭藍色右氣泡 如果單元格值大於或小於VBA代碼中的特定值,則運行或觸發宏

例如,如果單元格A1中的值在10到50之間,請運行macro1,如果該值大於50,則運行macro2。 要在Excel中解決此任務,請應用以下VBA代碼。

1。 右鍵單擊要基於單元格值執行宏的工作表選項卡,然後選擇 查看代碼 從上下文菜單中,然後在打開的 適用於應用程序的Microsoft Visual Basic 窗口,將以下代碼複製並粘貼到空白模塊中:

VBA代碼:如果單元格值大於或小於以下,則運行宏:

Private Sub Worksheet_Change(ByVal Target As Excel.Range)
    If Target.Cells.Count > 1 Then Exit Sub
    If IsNumeric(Target) And Target.Address = "$A$1" Then
        Select Case Target.Value
        Case 10 To 50: Macro1
        Case Is > 50: Macro2
        End Select
    End If
End Sub

基於單元格值1的doc運行宏

備註:在上面的代碼中:

A1 是包含要基於其運行宏的特定值的單元格;

情況10至50:Macro1:表示該值在10到50之間,運行Macro1;

案例> 50:Macro2:這意味著如果該值大於50,請運行Macro2。

請根據需要更改這些宏名稱和條件,並且您還可以在 Case 外殻 腳本。

2。 然後保存並關閉此代碼窗口,現在,當您在單元格A10中輸入的值介於50到1之間時,將觸發Macro1,如果輸入的值大於50,則將執行Macro2。


箭頭藍色右氣泡 如果單元格值等於帶有VBA代碼的特定文本,則運行或觸發宏

例如,如果要基於單元格中的特定文本觸發宏,則在輸入文本“ Delete”的情況下運行macro1,在鍵入文本“ Insert”的情況下運行macro2。 以下代碼可以幫您一個忙。

1。 右鍵單擊要基於單元格值執行宏的工作表,然後選擇 查看代碼 從上下文菜單中,然後在打開的 適用於應用程序的Microsoft Visual Basic 窗口,將以下代碼複製並粘貼到空白模塊中:

VBA 代碼:如果單元格值是特定文本,則運行宏

Sub worksheet_change(ByVal target As Range)
Set target = Range("A1")
If target.Value = "Delete" Then
 Call Macro1
End If
If target.Value = "Insert" Then
Call Macro2
End If
End Sub 

基於單元格值2的doc運行宏

備註:在上面的代碼中,“刪除“和”插入”是您要基於其運行宏的單元格文本,並且 Macro1 Macro2 是您要基於文本執行的宏。 請根據需要更改它們。

2。 然後保存此代碼並關閉窗口,現在,當在單元格A1中輸入文本“ Delete”時,將觸發macro1,如果輸入文本“ Insert”,則將執行macro2。


相關文章:

Excel中單元格值更改時如何運行宏?

如何在Excel中打印之前自動運行宏?

如何基於從Excel的下拉列表中選擇的值運行宏?

如何通過單擊Excel中的超鏈接運行宏?

從工作簿中選擇工作表時如何運行宏?

最佳辦公生產力工具

🤖 Kutools 人工智慧助手:基於以下內容徹底改變數據分析: 智慧執行   |  生成代碼  |  建立自訂公式  |  分析數據並產生圖表  |  呼叫 Kutools 函數...
熱門特色: 尋找、突出顯示或識別重複項   |  刪除空白行   |  合併列或儲存格而不遺失數據   |   沒有公式的回合 ...
超級查詢: 多條件VLookup    多值VLookup  |   跨多個工作表的 VLookup   |   模糊查詢 ....
高級下拉列表: 快速建立下拉列表   |  依賴下拉列表   |  多選下拉列表 ....
欄目經理: 新增特定數量的列  |  移動列  |  切換隱藏列的可見性狀態  |  比較範圍和列 ...
特色功能: 網格焦點   |  設計圖   |   大方程式酒吧    工作簿和工作表管理器   |  資源庫 (自動文字)   |  日期選擇器   |  合併工作表   |  加密/解密單元格    按清單發送電子郵件   |  超級濾鏡   |   特殊過濾器 (過濾粗體/斜體/刪除線...)...
前 15 個工具集12 文本 工具 (添加文本, 刪除字符,...)   |   50+ 圖表 類型 (甘特圖,...)   |   40+ 實用 公式 (根據生日計算年齡,...)   |   19 插入 工具 (插入二維碼, 從路徑插入圖片,...)   |   12 轉化 工具 (數字到單詞, 貨幣兌換,...)   |   7 合併與拆分 工具 (高級合併行, 分裂細胞,...)   |   ... 和更多

使用 Kutools for Excel 增強您的 Excel 技能,體驗前所未有的效率。 Kutools for Excel 提供了 300 多種進階功能來提高生產力並節省時間。  點擊此處獲取您最需要的功能...

產品描述


Office選項卡為Office帶來了選項卡式界面,使您的工作更加輕鬆

  • 在Word,Excel,PowerPoint中啟用選項卡式編輯和閱讀,發布者,Access,Visio和Project。
  • 在同一窗口的新選項卡中而不是在新窗口中打開並創建多個文檔。
  • 將您的工作效率提高 50%,每天為您減少數百次鼠標點擊!
Comments (20)
Rated 5 out of 5 · 1 ratings
This comment was minimized by the moderator on the site
I need the following help
How to disable assigned macro button autometically based on cell value in excel?
This comment was minimized by the moderator on the site
Hallo,

ich bräuchte dafür ein Makro,

ich kann dieses Problem nicht alleine lösen, wäre super wenn mir jemand helfen könnte.

In M1 steht die Zahl 5, jetzt soll der Bereich von A83 bis A683 auf die Zahl 5 geprüft werden, sollte z.B. A111 die Zahl 5 enthalten, dann soll C111 + 1 ( wenn in C111 23 steht dann soll da 24 stehen). Genau so wenn in A444 eine 5 steht, dann soll C444 + 1 ( wenn C444 = 99 dann 100).
Immer wenn der Wert mit M1 übereinstimmt, dann soll diese Zelle in Spalte C immer wieder + 1 zählen. Also 23 +1 dann 24 + 1 dann 25 +1 usw usw.


Vielleicht kann mir da jemand helfen,

Vielen Dank im vorraus.

LG Stfan
This comment was minimized by the moderator on the site
Buongiorno,
vorrei eseguire una macro quando una in una cella viene inserito un controllo "if" o se viene inserita una data e non un numero.

Ad esempio se nella cella A1 inserisco: If(B2=0;vero;falso) e la macro leggendo vero mi nasconde lo sheet2 altrimenti mi scopre la sheet 2.

Come posso fare?
Riesco a far funzionare il tutto se inserisco in A1 manualmente un valore (in questo caso vero o falso).

Grazie
This comment was minimized by the moderator on the site
Hello, Carlo,
In fact the second code in this article can solve your problem.
Note: You just need to change the text to True and False into the code, and change the code name to your own.
Sub worksheet_change(ByVal target As Range)
Set target = Range("A1")
If target.Value = "True" Then
 Call Macro1
End If
If target.Value = "False" Then
Call Macro2
End If
End Sub 


Please try again, thank you!
This comment was minimized by the moderator on the site
Buongiorno,
ho provato il listato che permette di richiamare 2 macro al cambio del valore di una cella, se quel cambio deriva da una funzione "se" non funziona, se digito i valori (vero o falso) funziona.

Come posso ovviare?
Eventualmente come potrei evitare di utilizzare il condizionale sulla cella e far verificare al listato se la cella che deve far avviare le macro è compilata o meno?

grazie
This comment was minimized by the moderator on the site
Ciao skyyang. Spero tu possa aiutarmi. Ho un programmino in vba che basandosi su variazioni di prezzo di una cella (E1), collegata in DDE con una piattaforma di trading di borsa, fissa i prezzi: Massimo, Minimo, Apertura, Chiusura, per poi passare alla riga successiva in base a un intervallo temporale impostato all'apertura del foglio elettronico. L'algoritmo da me sviluppato fa si che nelle colonne: "BH" e "BI" vengano visualizzati i prezzi di acquisto e di vendita, ma solo quando soddisfatte le condizioni date, altrimenti le celle non restituiscono nessun valore. Quello di cui avrei bisogno è di un avviso sonoro .wav che mi avvisi quando viene restituito un valore, di acquisto o di vendita, in modo di non dover fissare lo schermo per 14 ore al giorno. Ho provato a inserire un codice "SoundMe()" trovato on-line, ma suona ogni volta che c'è un nuovo massimo o un nuovo minimo nella riga in cui il programma sta aggiornando i prezzi. Pensi che il problema si possa risolvere? Grazie per l'attenzione
Stefano
This comment was minimized by the moderator on the site
Hi,
How to modify this code base on cell A1 formula calculation result
Sub Worksheet_Calculate()
Please help

Private Sub Worksheet_Change(ByVal Target As Excel.Range)
If Target.Cells.Count > 1 Then Exit Sub
If IsNumeric(Target) And Target.Address = "$A$1" Then
Select Case Target.Value
Case 10 To 50: Macro1
Case Is > 50: Macro2
End Select
End If
End Sub
Rated 5 out of 5
This comment was minimized by the moderator on the site
Hello, FG,
To make the code work in formula cells, please apply the below code:
Private Sub Worksheet_Change(ByVal Target As Excel.Range)
    On Error Resume Next
    If Target.Cells.Count > 1 Then Exit Sub
    If IsNumeric(Target) And Target.Address = "$A$1" Then
        Select Case Target.Value
        Case 10 To 50: macro1
        Case Is > 50: macro2
        End Select
    ElseIf (Not Intersect(Range("$A$1"), Target.Dependents) Is Nothing) Then
        Set Rg = Intersect(Range("$A$1"), Target.Dependents)(1)
        Select Case Rg.Value
        Case 10 To 50: macro1
        Case Is > 50: macro2
        End Select
    End If
End Sub

Please have a try, hope it can help you!
This comment was minimized by the moderator on the site
Thank you very much! It now works :)
This comment was minimized by the moderator on the site
Hi!

Im very new to VBA and I tried this solution for an excel-sheet I have. I basically just have a long list in excel, where you in column T should type Yes or No, and I would like it to, If typed Yes, run a macro... I tried a lot of different ways of defining the range but nothing works.

Sub worksheet_change(ByVal target As Range)

Set target = Range("T:T")
If target.Value = "Yes" Then
Call Macro1
End If

End Sub

I highlights this problem(runtime error- type mismatch): If target.Value = "Yes" Then

Can anybody help?

Best regards, Isabella
This comment was minimized by the moderator on the site
Hello, Westergaard
May be the following VBA code can help you: (Note: Please change the name of the Macro1 to your own code name)
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Range("T:T")) Is Nothing Then
If Target.Value = "Yes" Then
      Call Macro1
    End If
    End If
End Sub

Please try, hope it can help you!
This comment was minimized by the moderator on the site
Hello, Gilles,
You should insert a Spin Button (ActiveX Control) first, and then right clcik it, choose View code, then, copy and paste the below code between the existing scripts,
Dim xWSh As Worksheet
Dim xOL As OLEObject
Dim xRg As Range
Set xWSh = Application.ActiveSheet
Set xOL = xWSh.OLEObjects("SpinButton1") 'The name of the spin button
Set xRg = xWSh.Range(xOL.LinkedCell)
If IsNumeric(xRg) And xRg.Address = "$A$1" Then
        Select Case xRg.Value
        Case 10 To 50: Macro1
        Case Is > 50: Macro2
        End Select
End If

https://www.extendoffice.com/images/stories/comments/comment-skyyang/DOC-RUN-CODE.png

Please try, hope it can help you!
This comment was minimized by the moderator on the site
Bonjour,
je souhaiterais appliquer cette macro à mon code. Le problème est que la cellule s'incrémente via une toupie et le code ne reconnais pas le changement de valeur de la cellule.
Quand je saisie la valeur manuellement celà fonctionne correctement.

Merci d'avance
There are no comments posted here yet
Load More
Please leave your comments in English
Posting as Guest
×
Rate this post:
0   Characters
Suggested Locations