Call Macro on a specific sheet / Excel - excel

I want to run a macro on a specific sheet, in my case the sheet is called "Tablet".
If a cell value in "Tabelle1" changes, I want to run this macro in the "Tablet" sheet.
Code in my Tabelle1:
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address = "$C$2" Then
Call Delete_OptionB1
End If
End Sub
This part works.
Macro Code:
Sub Delete_OptionB1()
'
' Delete_OptionB1 Makro
'
With Worksheets("Tablet")
.Range("M2:AD2").Select
Selection.ClearContents
End With
End Sub
This wont do the job. Any suggestions how I get this working?

In your code using a with block
With Worksheets("Tablet")
.Range("M2:AD2").Select
Selection.ClearContents
End With
You are selecting .Range("M2:AD2").Select but then clearing the contents of the selection on whatever sheet may be active when you Delete_OptionB1. Change to include a . - .Selection.ClearContents.
Even better, get rid or the With...End With and Select altogether. A single line will do it all:
Sub Delete_OptionB2()
'
' Delete_OptionB1 Makro
'
Worksheets("Tablet").Range("M2:AD2").ClearContents
End Sub

Instead of …
Target.Address = "$C$2"
… better use the Application.Intersect method to make it work if Target is more than one cell (this can happen when you copy/paste a range):
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Target.Parent.Range("C2")) Is Nothing Then
Delete_OptionB1 'you don't need the Call statement
End If
End Sub
If Delete_OptionB1 is not in a public module but in a workbook use eg Tablet.Delete_OptionB1
Make Delete_OptionB1 public, and avoid using .Select and Selection. (also see How to avoid using Select in Excel VBA)
Public Sub Delete_OptionB1() 'make it public
ThisWorkbook.Worksheets("Tablet").Range("M2:AD2").ClearContents
End Sub

Place this in the Tabelle1 worksheet code area:
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Range("$C$2")) Is Nothing Then
Application.EnableEvents = False
Call Delete_OptionB1
Application.EnableEvents = True
End If
End Sub
Place this in a standard module:
Sub Delete_OptionB1()
'
' Delete_OptionB1 Makro
'
With Worksheets("Tablet")
.Range("M2:AD2").ClearContents
End With
End Sub

Related

Should I better modify some codes for .ClearContents?

I have simple macros for clearing cells on "Sheet1", which have drop down lists.
Sub reset1()
Range("D20:E21").ClearContents
Range("D8:E9").ClearContents
Range("D6:E7").ClearContents
End Sub
Sub reset2()
Range("D20:E21").ClearContents
Range("D8:E9").ClearContents
End Sub
Then I call these macros on "Sheet1" if the cell values change
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address = "$D$4" Then
Call reset1
End If
If Target.Address = "$D$6" Then
Call reset2
End If
End Sub
This code is written on the "Sheet1".
Normally it works but sometimes reset1() doesn't work.
I should then save and reopen the excel or run the macro manually.
Should I better modify some codes?
First problem is that with Range("D20:E21") it is not clear in which worksheet that range should be. Always specify the worksheet like Worksheets("Sheet1").Range("D20:E21").
Second problem is that if you .ClearContents in a Worksheet_Change event this is a cell change and triggers another Worksheet_Change event and so on. So it is recommended to disable events Application.EnableEvents = False before changing cells in Worksheet_Change event.
Third problem is that if you test Target.Address = "$D$4" and you copy paste a range where D4 is included your code will not run even if your cell D4 changed. Therefore you always need to work with Intersect.
Option Explicit
Sub Reset1(ByVal ws As Worksheet)
ws.Range("D20:E21,D8:E9,D6:E7").ClearContents
' alternative:
' Union(ws.Range("D20:E21"), ws.Range("D8:E9"), ws.Range("D6:E7")).ClearContents
End Sub
Sub Reset2(ByVal ws As Worksheet)
ws.Range("D20:E21,D8:E9").ClearContents
End Sub
Private Sub Worksheet_Change(ByVal Target As Range)
Application.EnableEvents = False
On Error Goto ENABLE_EVENTS ' in any case an error happens make sure events are enabeld again
If Not Intersect(Target, Me.Range("D4")) Is Nothing Then
Reset1 Me ' here we tell Reset1 to take `Me` as worksheet. Me refers to the worksheet `Target` is in.
End If
If Not Intersect(Target, Me.Range("D6")) Is Nothing Then
Reset2 Me
End If
ENABLE_EVENTS:
Application.EnableEvents = True
If Err.Number Then
Err.Raise Err.Number
End If
End Sub

Why does a macro assigned to a cell fail?

I have a macro assigned to a cell that executes once clicked on. The macro involves SAP scripting, which if ever interrupted (via CTRL+DEL+ALT), also causes my previously clickable cell to stop working.
I can run the macro via Developer yet the cell is not working. Note that the code provided below is pasted in the sheet where the clickable cell is, not in ThisWorkbook.
Option Explicit
Private Sub Worksheet_SelectionChange(ByVal target As Range)
If Selection.CountLarge = 1 Then
If Not Intersect(target, Range("A10")) Is Nothing Then
Call FolderPicker
End If
End Sub
Any ideas what might be causing the issue?
You need to close all if statements.
Option Explicit
Private Sub Worksheet_SelectionChange(ByVal target As Range)
If Selection.CountLarge = 1 Then
If Not Intersect(target, Range("A10")) Is Nothing Then
Call FolderPicker
End If
End If
End Sub
You could use:
Option Explicit
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
'Check count how many cells affected to avoid errors
If Target.Count = 1 Then
If Not Intersect(Target, Range("A10")) Is Nothing Then
Application.EnableEvents = False 'Disable events to avoid pointless code trigger
Call FolderPicker
Application.EnableEvents = True
End If
End If
End Sub

How to Run a Macro if the cell value changes

I created a macro that filters based on a cell value which works fine.
Range("A1:L1").AutoFilter Field:=4, Criteria1:=Range("U1")
I need this macro to run everytime the cell value changes.
I wrote a macro but it is not working i dont get any errors just nothing happens.
I tried:
Private Sub Worksheet_Tabelle1(ByVal Target As Range)
If Target.Address = "$U$1" Then
Application.EnableEvents = False
Range("A1:L1").AutoFilter Field:=4, Criteria1:=Range("U1")
Application.EnableEvents = True
End If
End Sub
This version should just execute the code and not call a macro. I changed the Worksheet_xxxxx to the sheet name and tried other things.
I also tried:
Private Sub Worksheet_Arbeitstabelle(ByVal Target As Range)
If Target.Address = "$U$1" Then
Call Macro1
End If
End Sub
This version should call the following Macro:
Sub Macro1()
Range("A1:L1").AutoFilter Field:=4, Criteria1:=Range("U1")
End Sub
I put all the Private Sub macros on the Worksheet and the Macro1 in a modul.
The file is .xlsm and doesnt have any problem running other macros so i dont know why its not working. My guess is i probably did something wrong with the names so here are the names:
Try this:
Dim KeyCells As Range
' The variable KeyCells contains the cells that will
' cause an alert when they are changed.
Set KeyCells = Range("A1:C10")
If Not Application.Intersect(KeyCells, Range(Target.Address)) _
Is Nothing Then
' Display a message when one of the designated cells has been
' changed.
' Place your code here.
MsgBox "Cell " & Target.Address & " has changed."
End If
End Sub
I changed:
Private Sub Worksheet_Arbeitstabelle(ByVal Target As Range)
To:
Private Sub Worksheet_Change(ByVal Target As Range)
#Siddharth Rout linked me to:
Why MS Excel crashes and closes during Worksheet_Change Sub procedure?
Here it is explained that its not necessary to add the name of the Sheet after Worksheet_
because the code is stored in the sheet so no need to tell it where to do stuff since its not in a module

How to trigger code when cell value is cleared?

I'm running a Worksheet_Change sub that checks if the changed cell is in a specific column and then autofits that column.
Public Const startCol = 7 '(declared in a separate module)
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Column = startCol Then
Target.Columns.AutoFit
End If
End Sub
My problem is, this macro is only run if something is put in the cell or the cell's value changes, not if the cell's value is cleared or the cell is deleted entirely.
Try this code:
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Column = startCol Then
Columns(startCol).AutoFit
End If
End Sub
The Target is a range, you can then check if the range's value is equal to "" empy string ->
If Target.Value2 = "" Then MsgBox ("Emptied cell " & Target.Address)
Here is a kind-of solution, if you are wanting worksheet changes in column 7 AND deletion of contents in column 7 (via the delete key) then this kinda might be reasonable:
In ThisWorkbook section
Private Sub Workbook_Open()
Application.OnKey "{DELETE}", "ColFit"
End Sub
Private Sub Workbook_BeforeClose(Cancel As Boolean)
Application.OnKey "{DELETE}"
End Sub
In a module
Sub ColFit()
Select Case TypeName(Selection)
Case "Range"
Selection.ClearContents
Worksheets("Sheet1").Columns("G:G").AutoFit
Case "ChartArea"
ActiveChart.Parent.Delete
Case "PlotArea"
ActiveChart.Parent.Delete
End Select
End Sub
On the Worksheet
Private Sub Worksheet_selectionChange(ByVal Target As Range)
Worksheets("Sheet1").Columns(startCol).AutoFit
End Sub
save and reopen, now some more bases are covered ;)
also consider(in ThisWorkbook):
Private Sub Workbook_WindowActivate(ByVal Wn As Window)
Application.OnKey "{DELETE}", "ColFit"
End Sub
Private Sub Workbook_WindowDeactivate(ByVal Wn As Window)
Application.OnKey "{DELETE}"
End Sub
which lets you work with multiple books without issues

Excel to voice cells' value whenever it is selected with VBA

I'm triyin to achieve that Excel "says" the value of a cell when placing on it.
I've got this code but i'm able to hear cells' value only after i select another one. Can you help me?
Sub Worksheet_Change(ByVal Target As Range)
Application.EnableEvents = True
Set Target = ActiveCell
Application.Speech.Speak (Target)
End Sub
If you want Excel to "say" whatever you enter in a cell, first run this short macro, then make entries:
Sub WhatDidYouEnter()
Application.Speech.SpeakCellOnEnter = True
End Sub
and if you want Excel to "say" whatever you have Selected, then the Event Macro:
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
With ActiveCell
If .Value <> "" Then Application.Speech.Speak (.Value)
End With
End Sub
will do the trick.
Try this out:
Option Explicit
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
Debug.Print Target.Address
End Sub
Then change it to speak, and not to debug. :)

Resources