VBA:Trigger macro on column filter - excel

Is there a way we can trigger a macro function on column filter in excel??
Please help
Thanks.

I was just thinking if I can post this answer. I guess some of you will not like it as it is not direct answer by presentation of bypass solution. However I think I can show that idea as we don't have all project assumptions in the question.
Let's agree- we all know that there is no event which fires after we change filtering. However, I see one option.
Changing filter could fire Worksheet_Calculate event (not Worksheet_Change). If there is any single formula within your sheet than we will fire that event each time we change filtering criteria using our mouse.
Step 1. put any single formula in the sheet, like in cell ZZ1 where =ZZ2
Step 2. I assume that our data range starts in Range(A1) and we have titles in first row (see the picture). I assume also there is nothing below that area.
Step 3. Put that following solution in Sheet1 module.
Private Sub Worksheet_Calculate()
If ActiveSheet.Name = "Sheet1" Then
If Cells(Rows.Count, 1).End(xlUp).Row = 1 Then
MsgBox "No data available"
Else
MsgBox "There are filtering results"
End If
End If
End Sub
Step 4. Using filter would fire that event and result with following situations:
I hope someone will like it and can use that. Even if it's only a bypass idea.

Related

Filling a range of cells with the same value using drop-down list

We all know that Excel has some counter-intuitive behaviours and it is, I believe, one of them:
When you select a range of few cells, starting your selection with the cell with data validation list and choose value from drop-down list: only one cell changes (the one containing drop-down list) instead of all selected.
Sometimes a few magic keyboard shortcuts such as CTRL+d, or combination of CTRL+' and CTRL+ENTER can fix this behaviour, but from my experience clients doesn't like to learn some new hacks, they just want to work everything in as simple way as possible.
I found even similar questions on SO e.g. here:
Adding same drop-down value to multiple cells simultaneously
I know that this is very simple code, but following few lines of code make my life easier, and I am sure this will help somebody too. Code in Worksheet module of course:
Option Explicit
Private Sub Worksheet_Change(ByVal Target As Range)
' MACRO FILLS THE WHOLE SELECTED RANGE
' WITH THE SAME VALUE USING DROP-DOWN LIST
' IN JUST ONE ACTIVE CELL
' change to false if all selected cells should be filled with value
Const FILL_VISIBLE_CELLS_ONLY As Boolean = True
' detecting if dropdown list was used
'
' I am using very clever solution by JvdV from SO
' ~~~~> stackoverflow.com/questions/56942551/
'
' If after edit we're in the same cell - drop-down list was used
' I know that may be also drag&drop or copy-paste
' but it seems no matters here.
' Warning! Should be add one more check if someone used
' 'accept OK character' next to formula bar, not implemented here.
'
If ActiveCell.Address <> Target.Address Then Exit Sub
' preventing error which sometimes occurs
If IsEmpty(ActiveCell.Value) Then Exit Sub
' fill a range or visible range with activeCell value
If FILL_VISIBLE_CELLS_ONLY Then
Selection.Cells.SpecialCells(xlCellTypeVisible) _
.Value = ActiveCell.Value
Else
Selection.Value = ActiveCell.Value
End If
End Sub
When you select a Range of more than one Cell, is is important to distinguish between the Active Cell (the single highlighted cell) and the Selection (the entire selected range, including the Active Cell).
Then:
Any Content (such as Values or Formulas) that you enter into the Formula bar is input into the Active Cell only, not the entire Selection.
Any Formatting changes you make are applied to the entire Selection, not just the Active Cell.
An exception is when entering an Array formula which applies to the Selection.
Since in this case you are making a change to content not formatting, it is applied to only the Active Cell.
When considering the above, it is not counterintuitive but entirely consistent with the design and operation of the software.
However, from a UX experience this may seem counterintuitive simply because it defies your expectation. This is kind of like a "customer is always right" type situation, which can be very frustrating for programmers, but is essential that it be understood. You can read more about the concept in a series of well-written articles on the topic at https://www.joelonsoftware.com/2000/04/10/controlling-your-environment-makes-you-happy/ (disclosure: the author of these articles happens to be integral to the development history of both Excel and SO, but it is linked here on merit). It was written more than 20 years ago and is still every bit as relevant today.

Managing Excel Worksheet_Change Feature

I have created a spreadsheet which uses the Worksheet_Change feature and the code associated with that works very well. I can stop it firing unnecessarily when inside the module by using Application.EnableEvents = False.
However, while I've created a form to enter data directly into the next available row (again, that works fine in terms of entry) it doesn't cause the formulae in the sheet to calculate (even though auto calculation is on and re-enabled within the module). If I manually place my cursor in the row, hit F2 and simply press enter, everything then fires up.
I have tried to enter data directly into the cells, but of course the Worksheet_Change feature then kicks in again and the cursor isn't simply moving to the next adjacent cell ....
I've tried to check firs for any direct entry with the code below and if it looks like the user isn't entering directly into the cell, the Worksheet_Change is disabled:
Sub Worksheet_Change(ByVal Target As Range)
On Error GoTo eventhandler
Sheets(1).Range("a1").Select
LastCell2 = Sheets(1).Cells(Rows.Count, "A").End(xlUp).Row
Dim intersection As Range
Set intersection = Intersect(Target, Range("A3:F" & LastCell2))
If intersection.Row = LastCell + 1 Then
Exit Sub
End If
Application.EnableEvents = False
The code above is simply checking to see if data is being entered into the next empty cell and if that's the case I want it to just exit there but it isn't working.
So I actually have 2 problems :
the first is why this formula isn't triggering after entry via a vba form - I've used INDIRECT since there are other macros that delete rows by moving the remaining cells up and that was causing the count in the $A$3:$A$500 to reduce to $A$499 and then 498 etc - the addition is done depending on the system date and the transaction date so I get a current value and a future value using a standard sum statement:
=AD1-(SUMIF(INDIRECT("$A$3:$A$500"),"<="&TODAY(),INDIRECT("$E$3:$E$500")))+(SUMIF(INDIRECT("$A$3:$A$500"),"<="&TODAY(),INDIRECT("$F$3:$F$500")))
The second is why I can't enter data directly into the spreadsheet and trap the fact that I don't want it to do anything and simply allow the user to hit enter and move to the next adjacent cell to the one they just entered data into.
Is this a lost cause and am I trying to do too much here? I'm relatively new to coding and teaching myself so apologies if the standard and style isn't to everyone's taste.
Thanks in advance for any replies.

Insert Row in VBA

I am trying to create a loop in Excel to insert an entire row when there is a value change in column A. It goes through the loop once and works perfectly. It inserts the row like it is suppose to but when it loops and the value changes again it jumps straight to end sub rather than inserting a new row. I have tried to do this multiple ways.
Below is the simple loop I made to see if it works. This code works from the bottom up.
Do Until ActiveCell = ""
If ActiveCell.Value <> ActiveCell.Offset(-1, 0).Value Then
ActiveCell.EntireRow.Insert
ActiveCell.Offset(-1, 0).Select
Else
ActiveCell.Offset(-1, 0).Select
End If
Loop
It reads to me like you are attempting to circumvent the Change event. I suggest reading the documentation particularly the Worksheet_Changedocumentation. If you try and implement the Change event and are still having issues, I suggest you edit your original question to provide a bit more clarity and offer more information.
I'm assuming that this loop is part of a larger piece of code. If so, make sure that the code is returning to the bottom of the sheet (or whatever location is desired). Since you are telling the loop to stop at an empty cell, running the code again without resetting the position of activecell will automatically find and empty cell and exit the loop.
As you said, the actual code for adding the blank rows itself works well, so it makes sense to look at the code around it.
#Bradon As I can see your code,it might be going into infinite loop [assuming you are using WorkSheet_Change event to catch any change in sheet]
Any change in worksheet trigger WorkSheet_Change event; in your case inserting row into worksheet is triggering the Worksheet_Change event
I will suggest you to post your entire code if possible
or
change you code like below [still assuming you are using WorkSheet_Change event]
add new sheet say "Config" and only once manually set A1 value to "True"
In worksheet change event use if condition
if Sheets("Config").Range("A1").Value = "True" then
call MyProcedure
end if
In Procedure
sub MyProcedure()
Sheets("Config").Range("A1").Value = "False"
your Do while loop here
Sheets("Config").Range("A1").Value = "True"

VBA/Excel: Flow Chart Formula

I'm sorry if this question is vague or answer exists, but struggling to find what I'm looking for.
I have created a sheet (VBA generated) where the user is required to fill in certain cells in a table. As multiple users are going to be editing the document, I want to automate a 'flow chart' type answer to standardize the document.
I.e. if in the first cell the user input is "No", then the remaining cells in the table default to "N/A". If the input is "Yes", then the user moves on to filling out the next box in the table. I was also going to use a drop down list to ensure the correct user input.
Does anyone have any suggestions of what I can research for a method to achieve this? Was thinking of having the cell formula, but this will delete after user input so wanted a method where the formula would remain even if the user input is deleted.
Thanks for any help.
The answer would be to use the worksheet_change event. However your problem is you are creating the sheet programatically. If you are using a template for your sheet you can just attach the code to the template, other wise you will have to create the code in your workbook and use the Workbook_sheetchange event
Private Sub Workbook_SheetChange(ByVal Sh As Object, ByVal Target As Range)
If Sh.Name = "sheet1" Then
If Target.Address = "$A$5" Then 'I'm assuming cell A5 is your first cell, change as required
If UCase(Sh.Range("a5")) = "NO" Then
Sh.Range("a10") = "#N/A" 'repeat for all cells you want to be NA
End If
End If
End If
End Sub

Simple vba program in Excel

Sub TEST()
If cells(i, "R").Value <> "UK" Then
cells(i, "R").Interior.ColorIndex = 3
End If
End Sub
If I run this program it throws application defined error \
I am new to Excel (beginner)
How to correct this error!!!
Thanks In advance
I think the issue is "R" that I know of the cells method takes 2 parameters one is rows the other is columns (in that order) but this is done by number not letter so if you change it to cell(1,18) then the code above works fine.
This link may also be useful to learn more, among other things it describes how you would normally select a range first as I believe your code above will assume the currently selected page, however you might want to run in on a button click from another page or as soon as the spreadsheet opens.
http://msdn.microsoft.com/en-us/library/office/ff196273.aspx
The problem is that the variable i has not been assigned a value. VBA assumes that it is zero. Since i is used to determine the row of the cell, Excel throws an exception because there is no row 0!
First you have to define i variable
for example: Dim i as variant

Resources