跳到主要内容

 如何在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。

请根据需要更改这些宏名称和条件,并且您还可以在 案例 脚本。

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 Tab 为 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