VBA to format cells based on another cell not working - vba

SOLVED: FOUND MY OWN WORKSHEET ERROR
The problem I was having was trying to use two worksheet_change events in the same workbook. Because I thought that was possible, I was just renaming the worksheet event in question when I received an error, thinking nothing of it. Both my original code and the answer provided work, when combined with my other worksheet_change event.
Thanks everyone.
Original Request:
I am trying to run a macro that does this:
every time cell r6 changes, run a macro that looks to see if the value in cell s9 is > or < 1, then format cells s9:t100 based on that.
I have the macro on its own to do the second part:
sub macro1()
If Range("S9").Value < 1 Then
Range("S9:S100,T9:T100").Select
Selection.NumberFormat = "0.0%"
Else
Range("S9:S100,T9:T100").Select
Selection.NumberFormat = "#,##0"
End If
end sub
This macro run on its own, works exactly as I want and formats the cells.
Then I have the worksheet event to call up that macro:
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address = "$R$6" Then
Call Macro1
End If
End Sub
When it is run to call up the same macro, it does not format the cells. They just stay as a % regardless of when cell r6 changes.
Any ideas why the worksheet event causes the macro to not work?

Try passing the worksheet object to your macro. This fully qualifies the Ranges to make sure you're working on the right area.
Also, you don't need to Select at all. Just use the range and directly change the settings.
Public Sub Macro1(ws as Worksheet)
If ws.Range("S9").Value < 1 Then
ws.Range("S9:S100,T9:T100").NumberFormat = "0.0%"
Else
ws.Range("S9:S100,T9:T100").NumberFormat = "#,##0"
End If
end sub
Sub test()
Macro1 ActiveSheet
End Sub
And in your Worksheet_Change...
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Address = "$R$6" Then
Macro1 Target.Worksheet
End If
End Sub

Related

Update a cell value with Row and Column number for use in indirect function based on which cell is selected

Hi I have a spreadsheet similar to below
Where when I click on a cell (red cell), I want to return the row and column number to another cell for use in an indirect lookup (blue cell)
Ideally I want to only update the cell value if it's within a set range or at least limit it only to that worksheet for error handling.
Hope that's clear... not an easy thing to google. My experiments with
Private Sub Worksheet_SelectionChange(ByVal Target As Excel.Range)
MsgBox ActiveCell.Row
End Sub
Have returned nothing, not even a message box even though macros run fine. Any ideas?
Based on your example. Make sure your code is in the appropriate sheet module, not a standard module and make sure Application.EnableEvents=True (your existing code should have done something).
Private Sub Worksheet_SelectionChange(ByVal Target As Excel.Range)
If Intersect(Target(1), Range("C4:H9")) Is Nothing Then Exit Sub
Range("J3").Value = Cells(Target(1).Row, 2) & "," & Cells(3, Target(1).Column)
End Sub
Use this in the worksheet's private code sheet.
Option Explicit
Private Sub Worksheet_SelectionChange(ByVal Target As Range)
If Not Intersect(Target.Cells(1), Range("C4:H9")) Is Nothing Then
Range("C4:H9").Interior.Pattern = xlNone
Cells(3, "J") = Join(Array(Cells(Target.Cells(1).Row, "B"), _
Cells(3, Target.Cells(1).Column)), Chr(44))
Target.Cells(1).Interior.ColorIndex = 3
End If
End Sub

Excel/VBA changing date when there are changes to the workbook

is it possible in Excel to insert today's date into a Workbook/sheet only when the data inside the sheet is changed.
So what I mean by this is that there is a workbook with several sheets and if somebody makes changes to this sheets I want to have my date updated that is in a specific cell. For better understanding lets just say that this cell is C5 of the first worksheet.
Thank you in advance
Try the code below:
Private Sub Worksheet_Change(ByVal Target As Range)
' check that the cell changed is not "C5"
If Intersect(Target, Range("C5")) Is Nothing Then
Application.EnableEvents = False
Range("C5").Value = Date
End If
Application.EnableEvents = True
End Sub

Sheet specific macro will not run when condition is met

I have a very simple workbook macro for testing and it is not executing when the condition is met. Do you know why? Macros are enabled and modules are working, however, sheet codes will not work. Any idea why?
Sub Worksheet_Change(ByVal Target As Range)
If Target.Address = "$J$3" Then
Call macro1
End If
End Sub
And then I tried
if A1 = "correct!"
msgbox "hey"
else <do nothing>
If I adjust anything in cell J3 or putting "correct!" in A1 in that sheet, neither code will execute. macro1's code is simply msgbox "Hey". Any idea what I can do?
Thanks!
I used Workbook_SheetChange and it worked for me:
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
If Sh.Name = "Sheet1" And Target.Address = "$J$3" Then
Call macro1
End If
End Sub
Sub macro1()
MsgBox "hello world!"
End Sub
I hope I'm understanding your post correctly, you want that once you modify a value in your worksheet at Cell J3, and the value in Cell A1 (at the same worksheet) is "correct!", that a MsgBox with "hey" will pop-up.
The code in your Worksheet_Change event is good, just modify the code in macro1 (which can be placed at another code module).
Sub macro1()
If Range("A1").Value = "correct!" Then
MsgBox "hey"
End If
End Sub
Option 2: using the Like operator
If Range("A1").Value Like "correct!" Then
MsgBox "hey"
End If

How to run macro if based on other cells which automatically changes by formula

As per subject, what I need is to run macro based on other cells.
Here is the case :
cells G3 until the end of row contains data used formula =IF(B3="";"";(SUMIF('Incoming Goods'!$F$3:$F$1048576;'Current Stock'!B3;'Incoming Goods'!$M$3:$M$1048576)-(SUMIF('Outgoing Goods'!$D$4:$D$1048576;'Current Stock'!B3;'Outgoing Goods'!$J$4:$J$1048576))))--> i need to convert this formula to VBA
cells H3 should contain : If G3.value = 0 then "Out of Stock", else " "
And this sheet must be calculate every time data in G3 change automatically or any additional data on this sheet.
Already tried this code :
Private Sub Worksheet_Calculate()
Dim Current As Worksheet
Dim Rng1 As Range
Dim Target As Range
Set Current = Worksheets("Current Stock")
Set Rng1 = Current.Range("G:G")
Set Target = Range("H:H")
For Each Rng1 In Target
If Rng1.Value2 = "0" Then
Target.Value2 = "Out Of Stock"
Else
Exit Sub
End If
Next
End Sub
However, above code is Not working. Already try using Private Sub Selection Change() and Private Sub Selection Change() but still not working.
Any suggestion?
Thanks in advance
the answer to the first part is below:
ActiveCell.FormulaR1C1 = _
"=IF(R[2]C[1]="""","""",(SUMIF('Incoming Goods'!R3C6:R1048576C6,'Current Stock'!R[2]C[1],'Incoming Goods'!R3C13:R1048576C13)-(SUMIF('Outgoing Goods'!R4C4:R1048576C4,'Current Stock'!R[2]C[1],'Outgoing Goods'!R4C10:R1048576C10))))"
handy tip: to convert any excel formula to code, hit the record macro button, then click on the cell, press F2 key, then press enter, and stop recording macro. The code will now be in its own module in the vba editor.
This should do what you want.
Private Sub Worksheet_Change(ByVal Target As Range)
If Target.Cells.Count > 1 Then Exit Sub
If Not Application.Intersect(Range("A1"), Target) Is Nothing Then
If IsNumeric(Target.Value) And Target.Value > 200 Then
Call YourMacroName
End If
End If
End Sub

Pop up a message in vba

I am working on a file which in one sheet lets call it summary, I have formula that calculate the values which Ienter manually in other sheets, so I want to have an vba code to notify me by pop up message that the calculation result in summary sheet is <=0 when doing data entry in other sheets.
I have found below code which works fine with only one cell but if I want to extend it to other cells in the same row results in error. Suppose I want to extend it to B9:CZ9.
Private Sub Worksheet_Calculate()
If Me.Range("B9").Value <= 0 Then _
MsgBox "Leave is finished!"
End Sub
Possible background:
Private Sub Worksheet_Calculate()
With Me.Range("B9:CZ9")
If Application.CountIf(.Cells, "<=0") = .Cells.Count Then _
MsgBox "Leave is finished!"
End With
End Sub
Private Sub Worksheet_Calculate()
Dim RNG As Range
Set RNG = Selection
For Each c In RNG
If c.Value <= 0 Then
MsgBox "Leave is finished!"
End If
Next c
End Sub
If I understood you correctly, maybe this code helps you (you have to put this code to the source of the correct worksheet you want to work this code on):
Private Sub Worksheet_Calculate()
Dim leave As Boolean: leave = False
For Each c In Me.Range("B9:CZ9").Cells
If c.Value <= 0 Then: leave = True
Next
If leave Then: MsgBox "Leave is finished!"
End Sub
This code works when something is calculated in a cell, for example when you type =0 into any of them, and don't give you lots of messageboxes.
If you want this to work when anything changes, use Private Sub Worksheet_Change(ByVal Target As Range)
Remember that extension xlsx cannot contain VBA codes. Therefore after implementing the code to the worksheet you want this code works on, you have to save it as macro-enabled workbook.