Why does ActiveSheet.FilterMode returns False when sheet has filter? - vba

I'm using the following code in an attempt to detect a filter applied to a column in a table and then clear the filter:
If ActiveSheet.FilterMode Then ActiveSheet.ShowAllData
According to Microsoft documentation:
This property is true if the worksheet contains a filtered list in which there are hidden rows.
This doesn't seem to be the case since ActiveSheet.Filtermode only returns True if a cell inside the table where the filter is applied is selected.
First question: Is the documentation wrong? Documentation
Second question: Is my only option to select a cell inside the table to get the expression to return True?
PS I am using Excel 2010
Edit: Answer to Question 2, Non-select based methods to clear filters...
If ActiveSheet.ListObjects(1).Autofilter.FilterMode Then ActiveSheet.ListObjects(1).Autofilter.Showalldata

I can replicate both your issues on Excel 2013: both the buggy False on FilterMode and the error on ShowAllData.
In response to whether the documentation is wrong, I would say that it is missing a qualification to say that the ActiveCell should be in the ListObjects DataBodyRange. Perhaps the documentation is correct but that this is a bug that has not been addressed. Maybe you can update your question with a link to the documentation?
Re your second question - I agree that using this workaround is the most obvious solution. It seems a bit unpleasant to use Select but sometimes I guess this cannot be avoided.
This is how I did it using the Intersect function to check it the ActiveCell is currently in the area of the DataBodyRange of the ListObject:
Option Explicit
Sub Test()
Dim rng As Range
Dim ws As Worksheet
Dim lst As ListObject
'get ActiveCell reference
Set rng = ActiveCell
'get reference to Worksheet based on ActiveCell
Set ws = rng.Parent
'is there a Listobject on the ActiveCells sheet?
If ws.ListObjects.Count > 0 Then
Set lst = ws.ListObjects(1)
Else
Debug.Print "No table found"
Exit Sub
End If
'is cell is in the DataBodyRange of ListObject?
If Intersect(rng, lst.DataBodyRange) Is Nothing Then
'set the ActiveCell to be in the DataBodyRange
lst.DataBodyRange.Cells(1, 1).Select
End If
'now you can safely call ShowAllData
If ws.FilterMode = True Then
ws.ShowAllData
End If
End Sub
Edit
Further to #orson's comment:
What happens if you skip the If Intersect(rng, lst.DataBodyRange) Is Nothing Then and use If lst.AutoFilter.FilterMode Then lst.AutoFilter.ShowAllData End If ?
So, you can check the FilterMode of the ListObject itself and then as long as you have a reference to the ListObject you can use his code:
If lst.AutoFilter.FilterMode Then
lst.AutoFilter.ShowAllData
End If

An easier alternative can be to just AutoFit all rows:
Rows.AutoFit
The issue with that is that it will un-hide and auto fit all rows on the active sheet.
Update from http://www.contextures.com/excelautofilterlist.html
Dim list As ListObject
For Each list ActiveSheet.ListObjects
If list.AutoFilter.FilterMode Then
list.AutoFilter.ShowAllData
End If
Next

Related

Run time error 13 on For loop

I am trying to use a combobox in my user interface, but if none of the options are good for the user they can type it in but after if they have entered something I want to save it so next time it appears in the list. I have tried the following approach:
For i = Range("O3") To Range("O3").End(xlDown)
If Not i.Value = ComboType.Value Then
Range("O3").End(xlDown) = ComboType.Value
End If
Next i
But this gives the above error on the first line. I am not very familiar with For loops in VBA so I am hoping somebody can help me.
This is how to make the for-each loop from O3 to the last cell with value after O3:
Public Sub TestMe()
Dim myCell As Range
Dim ws As Worksheet
Set ws = Worsheets(1)
With ws
For Each myCell In .Range("O3", .Range("O3").End(xlDown))
Debug.Print myCell.Address
Next myCell
End with
End Sub
It is a good practise to declare the worksheet as well, because otherwise you will always work with the ActiveSheet of the ActiveWorkbook.

Excel VBA code to select all cells with data sometimes working

I once built a VBA button to automatically lock all cells with data in them. And it was working perfectly. Now I wanted to copy that button to another worksheet. So I created another button, copy and pasted the whole VBA over, then edited the worksheet names and range. And, it's only working like 5% of the time, the rest of the time, I'm getting an "Run-Time error '1004': No cells were found." I've tried a few fixed, changing Sheets to Worksheets, or adding a ", 23" to the specialcells argument. However, nothing is working right now. When I try stepping in, it sometimes say both rng and lckrng as empty, and sometimes only show lockrng as empty and not show rng at all. Problem is this used to be a working code, and now, it still works around 5% of time. Any idea why? Thank you very much!
Private Sub CommandButton1_Click()
Dim rng As Range
Dim lockrng As Range
Sheets("Uploading Checklist (M)").Unprotect Password:="signature"
Set rng = Range("A1:M14")
'Selecting hardcoded data and formulas
Set lockrng = Union(rng.SpecialCells(xlCellTypeConstants), rng.SpecialCells(xlCellTypeFormulas))
lockrng.Locked = True
Sheets("Uploading Checklist (M)").Protect Password:="signature"
End Sub
Maybe this is too simplistic, but it seems to do what you want. The animated .gif shows it working to "lock all cells with data in them". (I made the second button just for convenience). If nothing else it might be good to start from something like this that works and modify to suit your needs.
Dim cell As Range, sh As Worksheet
Sub Button4_Click()
Set sh = Worksheets("Sheet1")
sh.Unprotect Password:="s"
For Each cell In sh.UsedRange
If cell <> "" Then cell.Locked = True Else cell.Locked = False
Next
sh.Protect Password:="s"
End Sub
Sub Button5_Click()
Set sh = Worksheets("Sheet1")
sh.Unprotect Password:="s"
End Sub
The Union you are attempting will not work if either of the parameters is Nothing (i.e. you either have no constants in the range, or you have no formulas in the range).
Prior to doing the Union, you should check the parameters aren't Nothing but, once you start changing your code to do that, it would be just as simple to do the locking in two parts - so I recommend you rewrite the code as follows:
Private Sub CommandButton1_Click()
With Sheets("Uploading Checklist (M)")
.Unprotect Password:="signature"
With .Range("A1:M14")
'Lock any constants
If Not .SpecialCells(xlCellTypeConstants) Is Nothing Then
.SpecialCells(xlCellTypeConstants).Locked = True
End If
'Lock any formulas
If Not .SpecialCells(xlCellTypeFormulas) Is Nothing Then
.SpecialCells(xlCellTypeFormulas).Locked = True
End If
End With
.Protect Password:="signature"
End With
End Sub

Create an IF statement to check and remove the advanced filter [duplicate]

It seems older macros are not working. I have proper securtiy set to run VBA macros but when I have tried a few methods for clearing ALL filters on a worksheet, I get a compile error.
Here is what I have tried:
Sub AutoFilter_Remove()
'This macro removes any filtering in order to display all of the data but it does not remove the filter arrows
ActiveSheet.ShowAllData
End Sub
I have buttons on the sheets to clear all filters for ease of use for users since the sheets has a lot of columns that have filters on them.
Try this:
If ActiveSheet.AutoFilterMode Then ActiveSheet.ShowAllData
ShowAllData will throw an error if a filter isn't currently applied. This will work:
Sub ResetFilters()
On Error Resume Next
ActiveSheet.ShowAllData
End Sub
If the sheet already has a filter on it then:
Sub Macro1()
Cells.AutoFilter
End Sub
will remove it.
For tables try this to check if it's on and turn off:
If wrkSheetCodeName.ListObjects("TableName").ShowAutoFilter Then
wrkSheetCodeName.ListObjects("TableName").Range.AutoFilter
End if
To Turn back on:
wrkSheetCodeName.ListObjects("TableName").Range.AutoFilter
this works nice.!
If ActiveSheet.AutoFilterMode Then Cells.AutoFilter
That is brilliant, the only answer I found that met my particular need, thanks SO much for putting it up!
I made just a minor addition to it so that the screen didn't flash and it removes and subsequently reapplies the password on each sheet as it cycles through [I have the same password for all sheets in the workbook]. In the spirit of your submission, I add this to assist anyone else....
Sub ClearFilters()
Application.ScreenUpdating = False
On Error Resume Next
For Each wrksheet In ActiveWorkbook.Worksheets
'Change the password to whatever is required
wrksheet.Unprotect Password:="Albuterol1"
wrksheet.ShowAllData 'This works for filtered data not in a table
For Each lstobj In wrksheet.ListObjects
If lstobj.ShowAutoFilter Then
lstobj.Range.AutoFilter 'Clear filters from a table
lstobj.Range.AutoFilter 'Add the filters back to the table
End If
'Change the password to whatever is required
wrksheet.Protect Password:="Albuterol1", _
DrawingObjects:=True, _
Contents:=True, _
Scenarios:=True, _
AllowFiltering:=True
Next 'Check next worksheet in the workbook
Next
Application.ScreenUpdating = True
End Sub
I know this is a relatively old post and don't really like being a necromancer... But since I had the same issue and tried a few of the options in this thread without success I combined some of the answers to get a working macro..
Hopefully this helps someone out there :)
Sub ResetFilters()
On Error Resume Next
For Each wrksheet In ActiveWorkbook.Worksheets
wrksheet.ShowAllData 'This works for filtered data not in a table
For Each lstobj In wrksheet.ListObjects
If lstobj.ShowAutoFilter Then
lstobj.Range.AutoFilter 'Clear filters from a table
lstobj.Range.AutoFilter 'Add the filters back to the table
End If
Next 'Check next worksheet in the workbook
Next
End Sub
There are two types of filters in Excel:
Auto Filter
Advanced Filter
The Auto Filter feature lets you filter from the excel interface using those tiny dropdown buttons. And the Advanced filter feature lets you filter using a criteria range.
The ShowAll method removes the filters, as in, shows all the rows, but does not get rid of those Drop Down buttons. You have to set the AutoFilterMode property of the worksheet to FALSE to remove those buttons.
Here is a Sub that I use frequently to remove filters:
Sub RemoveFilters(ByRef WhichSheet As Worksheet)
If WhichSheet.FilterMode Then WhichSheet.ShowAllData
If WhichSheet.AutoFilterMode Then WhichSheet.AutoFilterMode = False
End Sub
This shows all the data, and removes the dropdown buttons. It comes in handy while stacking (copying and pasting) data from multiple sheets or workbooks. Hope this helps.
I found this workaround to work pretty effectively. It basically removes autofilter from the table and then re-applies it, thus removing any previous filters. From my experience this is not prone to the error handling required with the other methods mentioned here.
Set myTable = YOUR_SHEET.ListObjects("YourTableName")
myTable.ShowAutoFilter = False
myTable.ShowAutoFilter = True
This will work too:
If ActiveSheet.FilterMode Then cells.AutoFilter
I usually use this code
Sub AutoFilter_Remove()
Sheet1.AutoFilterMode = False 'Change Sheet1 to the relevant sheet
'Alternatively: Worksheets("[Your Sheet Name]").AutoFilterMode = False
End Sub
This will first check if AutoFilterMode is set (filtering is possible), then check if FilterMode is on (you are filtering on something) then turn off filtering.
Regarding Errors, i.e. protection - se other answers
Context added (my script is looping over sheets, which are then saved as CSV, hence the need to remove filters - but keep AutoFilterMode on, if set:
For Each WS In ActiveWorkbook.Worksheets
Select Case WS.Name
Case "01", "02", "03", "04", "05"
With WS
If WS.AutoFilterMode Then
If WS.FilterMode Then WS.ShowAllData
End If
' Processing data
End With
Case Else
' Nothing to see here
End Select
Next
Try something like this:
Sub ClearDataFilters()
'Clears filters on the activesheet. Will not clear filters if the sheet is protected.
On Error GoTo Protection
If ActiveWorkbook.ActiveSheet.FilterMode Or _
ActiveWorkbook.ActiveSheet.AutoFilterMode Then _
ActiveWorkbook.ActiveSheet.ShowAllData
Exit Sub
Protection:
If Err.Number = 1004 And Err.Description = _
"ShowAllData method of Worksheet class failed" Then
MsgBox "Unable to Clear Filters. This could be due to protection on the sheet.", _
vbInformation
End If
End Sub
.FilterMode returns true if the worksheet is in filter mode. (See this for more information.)
See this for more information on .AutoFilter.
And finally, this will provide more information about the .ShowAllData method.
Here's the one-liner I use. It checks for an auto-filter and if found, removes it.
Unlike some answers, this code won't create an auto-filter if used on a worksheet that is not auto-filtered in the first place.
If Cells.AutoFilter Then Cells.AutoFilter
All you need is:
ActiveSheet.AutoFilter.ShowAllData
Why? Like the worksheet, AutoFilter also has a ShowAllData method, but it doesn't throw an error even when auto filter is enabled without an active filter.
This works best for me.
I usually use the following before I save and close the files.
Sub remove_filters
ActiveSheet.AutofilterMode = False
End Sub
Simply activate the filter headers and run showalldata, works 100%. Something like:
Range("A1:Z1").Activate
ActiveSheet.ShowAllData
Range("R1:Y1").Activate
ActiveSheet.ShowAllData
If you have the field headers in A1:Z1 and R1:Y1 respectively.
Im using .filtermode if filter is on it returns true
Dim returnValue As Boolean
returnValue = worksheet1.FilterMode
if returnValue Then
worksheet1.ShowAllData
End If
Try this:
Sub ResetFilters()
Dim ws As Worksheet
Dim wb As Workbook
Dim listObj As ListObject
For Each ws In ActiveWorkbook.Worksheets
For Each listObj In ws.ListObjects
If listObj.ShowHeaders Then
listObj.AutoFilter.ShowAllData
listObj.Sort.SortFields.Clear
End If
Next listObj
Next ws
End Sub
This Code clears all filters and removes sorting.
Source: Removing Filters for Each Table in a Workbook, VBA
Here is some code for fixing filters. For example, if you turn on filters in your sheet, then you add a column, then you want the new column to also be covered by a filter.
Private Sub AddOrFixFilters()
ActiveSheet.UsedRange.Select
' turn off filters if on, which forces a reset in case some columns weren't covered by the filter
If ActiveSheet.AutoFilterMode Then
Selection.AutoFilter
End If
' turn filters back on, auto-calculating the new columns to filter
Selection.AutoFilter
End Sub
This thread is ancient, but I wasn't happy with any of the given answers, and ended up writing my own. I'm sharing it now:
We start with:
Sub ResetWSFilters(ws as worksheet)
If ws.FilterMode Then
ws.ShowAllData
Else
End If
'This gets rid of "normal" filters - but tables will remain filtered
For Each listObj In ws.ListObjects
If listObj.ShowHeaders Then
listObj.AutoFilter.ShowAllData
listObj.Sort.SortFields.Clear
End If
Next listObj
'And this gets rid of table filters
End Sub
We can feed a specific worksheet to this macro which will unfilter just that one worksheet. Useful if you need to make sure just one worksheet is clear. However, I usually want to do the entire workbook
Sub ResetAllWBFilters(wb as workbook)
Dim ws As Worksheet
Dim wb As Workbook
Dim listObj As ListObject
For Each ws In wb.Worksheets
If ws.FilterMode Then
ws.ShowAllData
Else
End If
'This removes "normal" filters in the workbook - however, it doesn't remove table filters
For Each listObj In ws.ListObjects
If listObj.ShowHeaders Then
listObj.AutoFilter.ShowAllData
listObj.Sort.SortFields.Clear
End If
Next listObj
Next
'And this removes table filters. You need both aspects to make it work.
End Sub
You can use this, by, for example, opening a workbook you need to deal with and resetting their filters before doing anything with it:
Sub ExampleOpen()
Set TestingWorkBook = Workbooks.Open("C:\Intel\......") 'The .open is assuming you need to open the workbook in question - different procedure if it's already open
Call ResetAllWBFilters(TestingWorkBook)
End Sub
The one I use the most: Resetting all filters in the workbook that the module is stored in:
Sub ResetFilters()
Dim ws As Worksheet
Dim wb As Workbook
Dim listObj As ListObject
Set wb = ThisWorkbook
'Set wb = ActiveWorkbook
'This is if you place the macro in your personal wb to be able to reset the filters on any wb you're currently working on. Remove the set wb = thisworkbook if that's what you need
For Each ws In wb.Worksheets
If ws.FilterMode Then
ws.ShowAllData
Else
End If
'This removes "normal" filters in the workbook - however, it doesn't remove table filters
For Each listObj In ws.ListObjects
If listObj.ShowHeaders Then
listObj.AutoFilter.ShowAllData
listObj.Sort.SortFields.Clear
End If
Next listObj
Next
'And this removes table filters. You need both aspects to make it work.
End Sub
This will clear only if you have filter and does not cause any error when there arent any filter.
If ActiveSheet.AutoFilterMode Then ActiveSheet.Columns("A").AutoFilter
I am using this approach for a multi table and range sheet as a unique way.
Sub RemoveFilters(Ws As Worksheet)
Dim LO As ListObject
On Error Resume Next
Ws.ShowAllData
For Each LO In Ws.ListObjects
LO.ShowAutoFilter = True
LO.AutoFilter.ShowAllData
Next
Ws.ShowAllData
End Sub
Wow. Logging in afterwards deleted all but a portion of the first line. My mistake. However, this will be terse.
For both tests
Enter text in A1 and A5 of Sheet1
Filter for blanks only.
Run either test
Enter text in A5
Try to filter!
Sub SubsequentFilterFails()
With Sheet1 'assumes code name is still Sheet1
.ShowAllData 'assumes a filter has been applied
.Range(.Cells(2, 1), .Cells(7, 1)).EntireRow.Delete
End With
End Sub
Sub SubsequentFilterWorks()
With Sheet1
.Cells.AutoFilter
.Range(.Cells(2, 1), .Cells(7, 1)).EntireRow.Delete
.Cells.AutoFilter
End With
End Sub
Thus, when filters are being cleared in order to clean the worksheet .Cells.AutoFilter will be used.
Loop AutoFilter columns, if column is activated(on) then reset a column filter, you may insert a new criteria after a loop. This code does not remove AutoFilter banner.
Dim iCol as Long
Dim ws as Worksheet
...
For iCol = 1 To ws.AutoFilter.Filters.count
If ws.AutoFilter.Filters(iCol).On Then ws.AutoFilter.Range.AutoFilter Field:=iCol
Next
...
ws.AutoFilter.Range.AutoFilter Field:=4, Criteria1:="AABBCC"
I found this answer in a Microsoft webpage
It uses the AutoFilterMode as a boolean .
If Worksheets("Sheet1").AutoFilterMode Then Selection.AutoFilter
You must select range of the table first before using ActiveSheet.ShowAllData

VBA vlookup reference in different sheet

In Excel 2007, I am looping through the values of column 4 in Sheet 2. Still in Sheet 2, I want to output the result of my vlookup formula into column 5. The vlookup formula needs to refer to Sheet 1 where the reference columns are. In order to do so I have the following formula
Range("E2") = Application.WorksheetFunction.VLookup(Range("D2"), _
Worksheets("Sheet1").Range("A1:C65536"), 1, False)
Problem, it returns error code 1004. I read that it was because I needed to Select Sheet 1 before running the formulas such as:
ThisWorkbook.Worksheets("Sheet1").Select
But then the searched value Range ("D2") doesn't belong to Sheet 1 and it still return code 1004 after having brought Sheet 1 into view.
What is the correct way to refer to a different sheet in this case?
try this:
Dim ws as Worksheet
Set ws = Thisworkbook.Sheets("Sheet2")
With ws
.Range("E2").Formula = "=VLOOKUP(D2,Sheet1!$A:$C,1,0)"
End With
End Sub
This just the simplified version of what you want.
No need to use Application if you will just output the answer in the Range("E2").
If you want to stick with your logic, declare the variables.
See below for example.
Sub Test()
Dim rng As Range
Dim ws1, ws2 As Worksheet
Dim MyStringVar1 As String
Set ws1 = ThisWorkbook.Sheets("Sheet1")
Set ws2 = ThisWorkbook.Sheets("Sheet2")
Set rng = ws2.Range("D2")
With ws2
On Error Resume Next 'add this because if value is not found, vlookup fails, you get 1004
MyStringVar1 = Application.WorksheetFunction.VLookup(rng, ws1.Range("A1:C65536").Value, 1, False)
On Error GoTo 0
If MyStringVar1 = "" Then MsgBox "Item not found" Else MsgBox MyStringVar1
End With
End Sub
Hope this get's you started.
The answer your question: the correct way to refer to a different sheet is by appropriately qualifying each Range you use.
Please read this explanation and its conclusion, which I guess will give essential information.
The error you are getting is likely due to the sought-for value Sheet2!D2 not being found in the searched range Sheet1!A1:A65536. This may stem from two cases:
The value is actually not present (pointed out by chris nielsen).
You are searching the wrong Range. If the ActiveSheet is Sheet1, then using Range("D2") without qualifying it will be searching for Sheet1!D2, and it will throw the same error even if the sought-for value is present in the correct Range.
Code accounting for this (and items below) follows:
Sub srch()
Dim ws1 As Worksheet, ws2 As Worksheet
Dim srchres As Variant
Set ws1 = Worksheets("Sheet1")
Set ws2 = Worksheets("Sheet2")
On Error Resume Next
srchres = Application.WorksheetFunction.VLookup(ws2.Range("D2"), ws1.Range("A1:C65536"), 1, False)
On Error GoTo 0
If (IsEmpty(srchres)) Then
ws2.Range("E2").Formula = CVErr(xlErrNA) ' Use whatever you want
Else
ws2.Range("E2").Value = srchres
End If
End Sub
I will point out a few additional notable points:
Catching the error as done by chris nielsen is a good practice, probably mandatory if using Application.WorksheetFunction.VLookup (although it will not suitably handle case 2 above).
This catching is actually performed by the function VLOOKUP as entered in a cell (and, if the sought-for value is not found, the result of the error is presented as #N/A in the result). That is why the first soluton by L42 does not need any extra error handling (it is taken care by =VLOOKUP...).
Using =VLOOKUP... is fundamentally different from Application.WorksheetFunction.VLookup: the first leaves a formula, whose result may change if the cells referenced change; the second writes a fixed value.
Both solutions by L42 qualify Ranges suitably.
You are searching the first column of the range, and returning the value in that same column. Other functions are available for that (although yours works fine).
Your code work fine, provided the value in Sheet2!D2 exists in Sheet1!A:A. If it does not then error 1004 is raised.
To handle this case, try
Sub Demo()
Dim MyStringVar1 As Variant
On Error Resume Next
MyStringVar1 = Application.WorksheetFunction.VLookup(Range("D2"), _
Worksheets("Sheet1").Range("A:C"), 1, False)
On Error GoTo 0
If IsEmpty(MyStringVar1) Then
MsgBox "Value not found!"
End If
Range("E2") = MyStringVar1
End Sub
It's been many functions, macros and objects since I posted this question. The way I handled it, which is mentioned in one of the answers here, is by creating a string function that handles the errors that get generate by the vlookup function, and returns either nothing or the vlookup result if any.
Function fsVlookup(ByVal pSearch As Range, ByVal pMatrix As Range, ByVal pMatColNum As Integer) As String
Dim s As String
On Error Resume Next
s = Application.WorksheetFunction.VLookup(pSearch, pMatrix, pMatColNum, False)
If IsError(s) Then
fsVlookup = ""
Else
fsVlookup = s
End If
End Function
One could argue about the position of the error handling or by shortening this code, but it works in all cases for me, and as they say, "if it ain't broke, don't try and fix it".

Does there exist a VBA command which does not change the formula of a cell, but its value?

Suppose in a worksheet the formula of R4 cell is =B1+B2, and its current value is 10.
A VBA command Range("R4").Value = 5 will change both its formula and its value to 5.
Does anyone know if there exists a VBA command which changes the value of R4 to 5, but does not change its formula, such that its formula is still =B1+B2?
PS: we can also achieve the same state in another way: 1) do a Range("R4").Value = 5 2) change the formula of R4 to =B1+B2 but without evaluating it. In this case, does there exist a VBA command which change the formula of a cell without evaluating it?
Edit: What I want to do is...
I would like to write a function, which takes a worksheet where some cells may be out of date (the formula does not match its value), and generates automatically a VBA Sub, this VBA Sub can reproduce this worksheet. The VBA Sub may look like:
Sub Initiate()
Cells(2,3).Value = 5
Cells(4,5).Value = 10
...
Cells(2,3).Formula = "=2+3"
Cells(4,5).Formula = "=C2+C2"
...
End Sub
Such that running Initiate() builds one worksheet with same values and formulas.
Without the VBA command I am asking, this Initiate() will be hard to generated.
You cannot change the value of a cell to something different than what the cell formula computes to.
Regarding your p.s.: You can probably change the formula of a cell without re-evaluation by changing the calculation mode to manual. But that would of course apply to the entire workbook, not just this one cell
EDIT: maybe a solution would be to temporarily save the formula of the cell in either a tag of that cell, or a hidden worksheet?
It is quite simple to change the result of a formula without changing the formula itself:
Change the value of of its argument(s). This is a Solver-type approach:
Sub ForceDesiredResult()
Dim r As Range
Set r = Range("B2")
With r
If r.HasFormula Then
.Formula = .Formula & "-5"
Else
.Value = .Value - 5
End If
End With
End Sub
Here is some very dirty code that will save all values of all formulas on the active sheet as custom properties of the sheet, and a 2nd sub that will mark red all cells where the value has changed from it's original value, while preserving all formulas. It will need some error-checking routines (property already exists, property doesn't exist,...) but should give you something to work with. Since I don't really understand your problem it's a bit hard to say ;)
Sub AddCustomProperty()
Dim mysheet As Worksheet
Dim mycell2 As Range
Dim myProperty As CustomProperty
Set mysheet = ActiveWorkbook.ActiveSheet
For Each objcell In mysheet.UsedRange.Cells
Debug.Print objcell.Address
If objcell.HasFormula Then Set myProperty = mysheet.CustomProperties.Add(objcell.Address, objcell.Value)
Next objcell
End Sub
Sub CompareTags()
Dim mysheet As Worksheet
Dim mycell2 As Range
Dim myProperty As CustomProperty
Set mysheet = ActiveWorkbook.ActiveSheet
For Each objcell In mysheet.UsedRange.Cells
Debug.Print objcell.Address
If objcell.HasFormula Then
On Error Resume Next
If mysheet.CustomProperties(objcell.Address).Value <> objcell.Value Then
objcell.Font.ColorIndex = 3
On Error GoTo 0
End If
End If
Next objcell
End Sub