Find/replace conditionally formatted cells - vba

I've been using a conditional format formula =OR(B2=B1,B2=B3) to highlight consecutive duplicates. I then use format painter to copy the formula to all columns in my excel table.
I have set up a button that will, amongst other things, copy a workbook into a new workbook. I now want to include the above formula in this macro. My final objective is to replace all of the cells found with this formula with an asterisk (*).
I first tried to just pop the formula into the macro as a starting point -
For Each sh In Destwb.Worksheets
With sh.UsedRange.FormatConditions _
.Add(Type:=xlExpression, Formula1:="=OR(B2=B1,B2=B3)")
.Interior.Color = RGB(198, 239, 206)
End With
Next sh
But this just makes a mess of seemingly randomly highlighted cells. I'm not sure where I've gone wrong. Even column B highlights are all wrong. Could the header in B1 affect this? It doesn't when I use the CF normally. How can I expand the CF into all columns uniquely?
Finally, how do I go about working a replacement of formatted cells into this formula? Or is there a quicker/easier way to meet this end-goal?
I didn't realise I could add custom text in that way. That's moved me a good couple of steps forward.
Taking Balinti's suggestion into consideration I've tried a workaround. I was making a couple of assumptions that turned out to be wrong. I have been able to enter the CF into the Array of data that I have in my original workbook. It's not as simple as putting it into a table, but by manually selecting the range in each column and inputting the CF I have made it work.
I also wasn't sure if the formatting would carry through to the new worksheet as I have used the Paste Special command to convert the array formula to values in the new sheet. It does, however, carry the formatting across which is very handy.
It's not the perfect solution for me but it appears to be working so far. I still need to test what happens when I change the date and get updated data. It would still be interesting to know if I can move this formatting into my macro though. Any tips?

Related

Vba email generator, subject from excel spreadsheet

I have a vba code that generates an email. I would like the subject to be the data from the first and last cells in my list. The thing is, my list isnt of a set length, sometimes it contains 5 pieces of data sometimes 8 etc. How do i tell vba to pick the first and last cell no matter the length of the list?
thanks
For me, best practice is to just have cells on your sheet that calculate the first and last row (different ways you can do that), then give those cells a range name such as FirstRow and LastRow. In your vba then you refer to these cells to make your code dynamic.
e.g:
firstRow = Range("FirstRow)
lastRow = Range("lastRow")
test = range(cells(firstRow,lastRow))
-- Note I have not written VBA in many many years so am writing the above from memory so it may be not be exact.
Of course you can do it all entirely in VBA using the xlDown method mentioned previously but I prefer the transparency of it being on the main page so that easily spot if something breaks.
Range("A1").End(xlDown).Value
Where the cell is where you want to start and the End part moves all the way to the end

Named Cells and Formulas In Excel

How do I utilize named cell references in Excel that aren't absolute. I want to be able to take a formula and be able to drag it across excel and have one name cell reference update to a different named cell as I move across.
For example: I want to keep RevenuePerStay going across the formulas row and have excel updated the cell reference to the number of people staying. So
400 should be RevenuePerStay * Stay400
600 should be `RevenuePerStay * Stay600`
I tried using mixed cell reference and relative cell references using the dollar sign but excel will not accept this.
Assuming your stays are in row 5:
For this worksheet, click on cell C7 and go to create a new named range called Stays and for the formula write =C$5$ and exit the name manager.
Now change your formula in C7 to being RevenuePerStay*Stays and drag it across. This will get the right amount of stays you want each time.
In explicit answer to your question: no you would never get the name in the formula to change unless you put all scenarios in the formula using multiple if statements.
If I understand your question correctly, this method seems convoluted because you can use =RevenuePerStay*C5 and drag over the row, and it should give the answer you want.
If you really want to take the advantage of named range and make it change dynamically, you will need to incorporate with INDIRECT like this:
=RevenuePerStay*INDIRECT("Stay"&C5)
But this is assuming you have all the named ranges defined properly such as Stay200, Stay400, Stay600, Stay800, Stay1000 like below. Otherwise it will not work.

SUMIFS returns 0 using dynamic criteria, with criteria range and sum range on another sheet

Anyone,
I've chatted with and called excel customer service with no luck. I used the formula builder (please see attached screenshot) to make sure each element of the formula is correct and returns the value for the criteria I'm trying to reference.
Everything is accurate, but it returns a value of 0. When I do the same thing in the actual sheet the data is stored in (and click a criteria cell within the criteria range) it returns the accurate value?! I'm not sure why it won't work on the other sheet. The values I am using to select are dynamic and change with a drop down. I have another, advanced, workbook (I did not create) that does the same thing and completes an even more complicated formula, but actually works so I'm not sure why this is returning a 0 value.
Photos and code/syntax: Dynamic Selection, Example 2 of it working, Example 1 of it working, Formula Builder, CountIFs, Advanced Spreadsheet working, VLOOKUP
=SUMIFS('GFEBS Pull'!Q:Q,'GFEBS Pull'!G:G,FMCOP!$C$20,'GFEBS Pull'!H:H,FMCOP!B23)
or:
=SUMIFS('GFEBS Pull'!Q:Q,'GFEBS Pull'!G:G,'FMCOP'!$C$20,'GFEBS Pull'!H:H,'FMCOP'!B23)
When I type ' around FMCOP sheet name, they disappear? I've also tried to lock the columns on the 'GFEBS Pull' sheet with no luck. Cell B23 is not locked because I'm going to copy the formula down to reference other cells. Any help is appreciated!
In this screenshot you can clearly see that both FMCOP!C20 ansd FMCOP!B23 have prefacing spaces; e.g. " HHC".
Since " HHC" will never match "HHC", fix the data returned from 'the lower table in the same screenshot'.
A Text-to-Columns, Fixed Width, Finish should do this. You could adjust the original formula like,
=SUMIFS('GFEBS Pull'!Q:Q, 'GFEBS Pull'!G:G, TRIM(FMCOP!$C$20), 'GFEBS Pull'!H:H, TRIM(FMCOP!B23))
I would caution against the latter 'bandaid' fix. Fix the original data; do not apply bandaids on-the-fly.

Excel formula within VBA

I have quite a few cells that contain formula, then with VBA the outcome of this formula is the value for a variable, like so:
On sheet in cell AS4:
=SUMPRODUCT(MAX((ROW($AE$4:$AE$997))*($AE$4:$AE$997<>"")))
and then in my VBA:
numRows = ws.Range("AS4").Value
However this is starting to get hard to keep track of which cell is feeding which variable, avoiding overwriting those cells on the sheet by accident, etc.
I need to be able to perform this calculation within VBA if I can, removing the need to have "calculation cells" on my sheet.
I have discovered there is a way to use formula with WorksheetFunction, but only found simple examples of this and cannot adapt it to my situation above.
numRows = WorksheetFunction.SumProduct(MAX((ROW($AE$4:$AE$997))*($AE$4:$AE$997<>"")))
Is not going to work...
Is there a way to do this, or am I better scrapping the idea of using formula and using a pure VBA method?
With help from SJR this was the answer:
numRows = [=SUMPRODUCT(MAX((ROW(Weights!$AE$4:$AE$997))*(Weights!$AE$4:$AE$997<>"""")))]
A bit more research taught me that evaluate(" ") can be just replaced with square brackets [ and ]. Although, if I had variables in the mix of this formula or the formula wasn't constant then I would have to use Evaluate.
I also needed to add the sheet name to the formula as this formula was no longer functioning within the sheet and AE4:AE997 was no longer referring to the correct sheet.
Doubling up on quotes is also necessary as it is code and sees " differently to a formula on the sheet

Link from cell in other sheet shows 0 but other sheet shows data cant get past this

Spent hours searching for any mention of this but no luck. Maybe someone here knows the answer. I developed a large application in excel. sheet1 receives data from a Com server that just places it there. This has been working for a long time with no problems.
I have sheet2 two with links from sheet 1 and formulas. Mostly I do all the processing in sheet1 change event because I got circular refernces when putting functions in a cell.
From yesterday, I have a problem that the cell in sheet 2 shows 0. When I go to the linked cell it has data. Sometimes numbers and sometimes text depending, but sheet 2 shows 0.
As well as the linked cells, I also screen scrape some data with a seperate process and place it sheet 3 to link across to other cells, so sheet2 will also contain links form this data. I spent today changing this so it places the data in directly in sheet1 instead of creating links. This is tedious and will cause other problems.
I checked options -> formulas. Right now it is set at max iterations 100; max change 100. I had reduced max iterations to stop some functions firing themselves recursively through the sheet change event. Now I raised it back to 100.
I deleted all the data saved the sheet started again and the same thing happened again.
e.g. sheet1 cell "A1" has a value of 10
sheet2 cell a1 has a formula of ='sheet1'!A1
sheet 2 cell A1 is showing 0
when I look in the formula bar I see the formula
This data was damaged down to row 42 the last row that had held data. below that the conditional formatting was the correct color even though the formulas looked identical and i could see nothing wrong to explain it, I dragged the formula from 44 upwards again and everything worked, but bizarrely, when I copied from sheet1 cells 1 to 44 and pasted a link back in, I still got 0.
When I run the system and the COM erver delivers a load and the change event fires etc, I end up back with the same problem.
Now when I add a new sheet and paste my links from sheet1 into this, it works as it should.
Right now after my attempts to fix it. All sheet1 and sheet2 columns are formatted general though previousy I had one column text and some others number. I can't control the format of sheet1 because excel just adapts to the data it receives regardless what I do.
I also keep checkng for application.enableevents and this is not the problem nor is worksheet calculate and in the options I have automatic claculation set
The only other routine running under sheet change in sheet 2 is a tidyup that clears out old data after the COM server has delivered a smaller number of rows.
It copies default data from unused cells in the sheet. I placed the right formatting and default such as blank or 0 depending on what is required. This has not in the past caused any issues and I cant see what it might do, though previously when I just tried puttng "" in the cells to be cleared that did cause nasty excel erros. but not now.
Does anyone have any ideas?
I don't know if this is still relevant, but I had the same issue and came here searching for an answer.
In my case, I realized the cell I was trying to copy was a merged cell (i.e. it provided a range) the formula was [='Sheet1'!B10:N10] and the result was 0 and not the text I wanted. so I changed the formula to ='USA-CA'!B10 and it worked.
hope this is helpful to someone else.
This little routine fixes it.
Sub fixformulas()
'fix formulas broken by excel for some reason
Cells.Replace What:="=", Replacement:="=", LookAt:=xlPart, SearchOrder _
:=xlByRows, MatchCase:=False, SearchFormat:=False, ReplaceFormat:=False
End Sub
All I can work out is that when excel copies the formulas and puts them back in place it corrupts the equals sign. Everything else is fine but as oon as I replace this the lights go on.
I'd rather know how to prevent it, but I hope nobody else suffers like I have.