VBA code for overriding blank looking cells in excel - excel

There are occasions when we use an IF formula, something like this in B1 for example =IF(A1=1,5000,""), and the results seem to be like either 5000 or a blank cells. But the blank cell is not actually blank as it contains a formula which has returned "" - that's why the cell looks blank.
When we drag the formula from B1 to B10 (say), then 10 cells are selected. And then I have written the below code to make the cells which have returned as "" to be empty.
Option Explicit
Sub delblanks()
For Each cell In Selection
If cell.Value = "" Then cell.Value = ""
Next
End Sub
...it triggers the error
variable not defined
How to fix this???

This here should fix it. Option Explicit gives an error when you do not declare your variables.
Option Explicit
Sub delblanks()
Dim cell As Range
For Each cell In Selection
If cell.Value = "" Then cell.Value = ""
Next
End Sub

Why not put an actual variable instead of just "" and delete it using your code?

Related

VBA Excel: Function not working on combined cells

I'm having problems with combined cells.
The following ranges are combined: G42:Q42, G43:Q43 and so on and so forth until G47:Q47
This code works fine when the cells arenĀ“t combined as descripted above, but I can't get it to work when the cells are merged
For Each cell In ventas.Range("G42:G47")
If (cell.Value = "") Then cell.ClearContents
Next
I've tried this but it's useless:
For Each cell In ventas.Range("G42:Q47")
If (cell.Value = "") Then cell.ClearContents
Next
Try this
Sub clearRange()
Dim c As Range
For Each c In ventas.Range("G42:Q47").Cells
If c.MergeCells = True Then
If c.MergeArea.Cells(1, 1) = "" Then c.MergeArea.ClearContents
Else
If c.Value = "" Then c.ClearContents
End If
Next
End Sub
The code checks if the cell is part of a merge and then only works on the first cell.
Working with merged cells can be very tricky.
combined cells can also be addressed as a single cell.
Say I combine C3:G7 I can run
ActiveWorkbook.Sheets(1).Cells(3, 3).Value = "test"
and the cell will display"test"
You can look up the name of the cell in the top left

How to add modification to all formulas from a selected range in excel

I would like to limit all of the formulas in a selected range of cells with an additional if statement.
Is it doable with the use of the VBA?
Let's say:
cell A1 contains =sum(B1;C1) but it can be any formula that a selected cell contains
after applying macro updated formula would be =if(D100>0;sum(B1;C1);0)
=if(D100>0;any formula in a cell ;0)
You can achieve this by using code like this:
Sub ModifyFormulas()
Dim cl As Range, formulas_cells As Range
Const template = "=if(D100>0,#,0)" '# will be replaced by old formula without '='
On Error Resume Next ' handle an error if there are no formulas in the range
Set formulas_cells = Range("A1:A10").SpecialCells(xlCellTypeFormulas)
On Error GoTo 0
If Not formulas_cells Is Nothing Then
For Each cl In formulas_cells
cl.Formula = Replace(template, "#", Mid(cl.Formula, 2))
Next
End If
End Sub
Without vba, I use the following method:
edit / replace the "=" with "xyxy" - this stops excel recalculating
then edit / replace "sum" with "if(D100>0;sum"
then edit / replace ")" with ");0)"
lastly replace "xyxy" with "="
and then it all works, done this often with my sheets when I have to change some calculations...

Azure Data Studio produced Excel spreadsheet displays cell values as text (not the result of the formula's execution)

Original Problem:
Within Azure Data Studio, I have saved the results of a SQL query into Excel spreadsheet. When I bring up the spreadsheet, a cell containing a formula (a URL hyperlink) is showing as text to display as opposed to results of executing the formula (a named visibly clickable hyperlink).
Here's the first three rows of raw data from the spreadsheet:
sourceTableNameA
sourceTableComposedKeyA
sourceTableComposedKeyA2
sourceTableNameB
sourceTableComposedKeyB
FCC_ASR_LI_20210202
=Hyperlink("https://maps.google.com/maps?q=28.537266254426,-97.794735431672","C.2655506")
https://maps.google.com/maps?q=28.537266254426,-97.794735431672
F3GIS_20210209
=Hyperlink("https://maps.google.com/maps?q=28.537266254426,-97.794735431672","{F4C8C17C-0702-4B08-ABC5-7ABF0BD76BAA}")
FCC_ASR_LI_20210202
=Hyperlink("https://maps.google.com/maps?q=29.709928035737,-96.912009716035","C.616145")
https://maps.google.com/maps?q=29.709928035737,-96.912009716035
F3GIS_20210209
=Hyperlink("https://maps.google.com/maps?q=29.709928035737,-96.912009716035","{7F77EAB2-3588-4023-921F-4C009FC91BDC}")
Solution A:
By clicking into the cell (ex: B2 above) and then pressing Return, the cell then turns into the results of the formula.
New Problem:
I have +20K of cells which I need to execute "Solution A". And manually executing "Solution A" +20K times is not an option.
Solution B (barely adequate):
After investing considerable time trying to fix this, I discovered a marginal solution. It is to select the contents of the column containing the formula-as-text, then search/replace the "=" character. While this does in fact convert the text into an actual formula for each cell, it leaves each cell looking like regular text instead of making it have the default appearance of a clickable link. This is causing me to have to then manually underline and select a different color for all of these cells.
Solution C (possible?):
My first thought was this is a job for an Excel Macro in VBA. And this is as close as I was able to get:
Public Sub Convert_To_Hyperlinks()
Dim Cell As Range
For Each Cell In Intersect(Selection, ActiveSheet.UsedRange)
If Cell <> "" Then
If Left(Cell, 1) = "=" Then
Evaluate (Cell)
Else
ActiveSheet.Hyperlinks.Add Cell, Cell.Value
End If
End If
Next
End Sub
This function works exactly as I need for cells (ex: C2 above) that contain a raw URL (i.e. the cell does not start with "=" character) which calls the ActiveSheet.Hyperlinks.Add Cell, Cell.Value for each cell giving the desired result. However, the code that detects if the cell (ex: B2 above) starts with "=" which calls Evaluate (Cell) doesn't work on the selected cells.
What VBA code can I use to replace Evaluate (Cell), if any, which would produce the same effect as Solution A?
In projects I have worked on I have found the following is often sufficient:
Cell.Value = Cell.Value
The beauty is that you can apply to ranges in one line.
Applying to your code with the loop:
Public Sub Convert_To_Hyperlinks()
Dim Cell As Range
For Each Cell In Intersect(Selection, ActiveSheet.UsedRange)
If Cell <> vbNullString Then
If Left$(Cell, 1) = "=" Then
Cell.Value = Cell.Value
Else
ActiveSheet.Hyperlinks.Add Cell, Cell.Value
End If
End If
Next
End Sub

Excel - Blank Cells?

I would like to return a blank cell from an if statement (Let's call this cell SHEET2!A1):
=IF(MAIN!E5=0,"",MAIN!E5)
However, if I call this:
=ISBLANK(SHEET2!A1)
The result is FALSE. I don't understand! I've tried resulting to NA() or just leaving the "" out of the formula, but to no effect. THE CELL IS NOT BLANK - Excel tells me so.
How do I result this formula to NOTHING?
BUZZYSIN
Yes you have to use VBA something like the below code
Sub delempty()
Dim Rng As Range
Set Rng = ActiveSheet.Range("A1:A10")
Dim i As Long
For i = 1 To 10
If Rng.Cells(i,1) = "" Then
Rng.Cells(i,1).ClearContents
End If
Next i
End Sub
If testing a cell containing a formula for the presence of "", you have to compare the result to "" rather than using ISBLANK:-
=A1=""
ISBLANK only works for cells which are completely empty.
You still need to wrap the isblank formula as an If statement or else by default it will only return true or false
Try syntax similar to this:
=if (istext(a1), a1,"")
Or
=if(isblank (a1), a1,"")

Excel formula in VBA code

So, in Sheet1 I have base of some names and it looks like this:
In Sheet2 I'm working with these names from Sheet1. I'm doing that in a way that I'm entering Code value in column A and in column B I get the Name, in column C I get the Last Name. That looks like this:
I've done this with formulas, entering it in the formula bar. For column A(or Name) I've used this formula: =IFERROR(VLOOKUP(A2;Sheet1!A:C;2;FALSE);"") and for column B(or Last Name) I've used this one: =IFERROR(VLOOKUP(A2;Sheet1!A:C;3;FALSE);""). I've dragged these formulas to row 20 and it works great.
Now, what I'd like to do is to put these formulas into Excel VBA code and them to work for noted range. I've just started to use VBA and I don't know how to do it in it, tried something but doesn't work, ..., I've done this so far. I'm new to this Excel/Macro/VBA thing so any help would be appreciated.
The below code will work if you type in your Code values in sheet2 and highlight them, and run this macro:
Selection.Offset(0, 1).FormulaR1C1 = "=IFERROR(VLOOKUP(RC[-1],Sheet1!C[-1]:C,2,FALSE),"""")"
Selection.Offset(0, 2).FormulaR1C1 = "=IFERROR(VLOOKUP(RC[-2],Sheet1!C[-2]:C,3,FALSE),"""")"
Selection.Offset(0, 1).Value = Selection.Offset(0, 1).Value
Selection.Offset(0, 2).Value = Selection.Offset(0, 2).Value
Edit: If you are wanting to update values as you type use (thank you #PeterAlbert for added optimisation!):
Private Sub Worksheet_Change(ByVal Target As Range)
'end if the user made a change to more than one cell at once?
If Target.Count > 1 Then End
'stop system activating worksheet_change event while changing the sheet
Application.EnableEvents = False
'continue if column 1(A) was updated
'and
'dont continue if header or row 1 was changed
If Target.Column = 1 And Target.Row <> 1 Then
With Target.Offset(0, 1) 'alter the next cell, current column +1 (column B)
'RC1 = current row and column 1(A) e.g. if A2 was edited, RC1 = $B2
'C1:C2 = $A:$B
.FormulaR1C1 = "=IFERROR(VLOOKUP(RC1,Sheet1!C1:C2,2,FALSE),"""")"
.Value = .Value 'store value
End With
With Target.Offset(0, 2) 'alter the next cell, current column +2 (column C)
'C1:C3 = $A:$C
.FormulaR1C1 = "=IFERROR(VLOOKUP(RC1,Sheet1!C1:C3,3,FALSE),"""")"
.Value = .Value 'store value
End With
End If
Application.EnableEvents = True 'reset system events
End Sub
Explinatioin of RC:
The FormulaR1C1 formula types are good to use when referencing a cell with respect to the current cell. There a few rules to remember:
The R stands for Row and C is for Column and the integer after it, if any, defines the row or column;
As a basis the RC formula references itself;
Any number following the R or C wraped in [] is an offset to itself, e.g. if you are in cell A1 and use R[1]C[1] you would be referencing cell B2;
Also any number following the R and C is an exact, e.g. if you reference R2C2 no matter the cell you are in would also point to B2; and
To complicate things if you were in cell C5, e.g. using Range("C5").FormulaR1C1 = and coded the follwing:
"=RC[-1]" references cell B5
"=RC1" references cell A5, more rightly $A5
"=R[1]C[-2]" references cell A6
"=Sum(C[-1]:C5)" is =Sum(B:E), more rightly =Sum(B:$E)
If I understand your question and comments correctly, you want to ensure that columns B&C always show you the right values based on your formula, but also want to protect (and maybe even hide the formula) from the users.
I'd suggest you use sheet protection instead: all you need to do is to unlock the cells you want the users to edit, i.e. select column A and in the _ Format cells_ dialog uncheck "Locked" in the Protection tab. Similarly for columns B&C, check "Hidden". Now right click the sheet name and select Protect Sheet. Once this is done, the user can edit column A - but will not see the formula in B&C and cannot edit those cells.
If for some reasons you need to ensure this in VBA, use the following code:
Private Sub Worksheet_Change(ByVal Target As Range)
Application.EnableEvents = False 'to prevent endless loop
With Target.Offset(, 2 - Target.Column).Resize(, 2)
.FormulaR1C1 = "=IFERROR(VLOOKUP(RC1,Sheet1!C1:C3,COLUMN(RC),0),"""")"
.Value = .Value
End With
Application.EnableEvents = True
End Sub
You need to place this in the module of the worksheet.

Resources