VBA Excel: Function not working on combined cells - excel

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

Related

Update Cell Content Based on Existing Reference Cells

I have the following situation:
I would like have EACH initial Ref. Cell cell and its associated blank cells, for example A2:A7, updated so that its results in the following data structure:
I have tried using formulas containing a combination of COUNT, COUNTBLANK, ROW() but have failed miserably in achieving the desired outcome.
Can you help?
In A2, formula copied down :
="1:"&COUNTA(B$2:B2)&":"&ROW(A1)-MATCH("zz",B$2:B2)+1
If with vba, maybe something like this ?
Sub Macro1()
For Each cell In Range("A2", Range("A" & Rows.Count).End(xlUp)).SpecialCells(xlCellTypeConstants)
If cell.End(xlDown).Row = Rows.Count Then Exit Sub
Set oEnd = cell.End(xlDown).Offset(-1, 0)
Set rngNum = cell
num = "'" & cell.Value & ":"
n = Range(cell, oEnd).Rows.Count
For i = 1 To n
rngNum.Value = num & i
Set rngNum = rngNum.Offset(1, 0)
Next i
Next cell
End Sub
But the weakness, the code will stop at the last row value in column A.
For example based on your first image, the code will stop at 3:1 while you are expecting this 3:1 row will change to 3:1:1 and the next row value is 3:1:2

Adding a formula in an active range using the contents of the cell in that range

I want to add a formula to a range of cells using the contents of the cell.
I am relatively new to VBA and I want to make a macro that reduces my work.
The result should be something like this. Using Round formula as an example.
For example, I select a range of cells and the macro adds the formula to the selected range using the contents of that cell. The below image might be clearer in explaining what I want.
Expected Result:
Sub ApplyRoundFormula()
For Each cell In Selection.Cells
If cell.HasFormula Then
StrCurrentFormula = cell.Formula
StrCurrentFormula = Mid(StrCurrentFormula, 2, 999)
cell.Formula = "=ROUND(" & StrCurrentFormula & ",0)"
ElseIf IsNumeric(cell) Then
cell.Formula = "=ROUND(" & cell.Value & ",0)"
End If
Next
End Sub
This script loops through each cell of a selected range (you can change Selection to any range reference), if it has formulas, it crops the equation mark from the beginning and puts the rest into a ROUND formula. If it doesn't have a formula but it has a numeric value, it puts that numeric value into a ROUND formula.

VBA code for overriding blank looking cells in 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?

If cells contains sum of two cells

I would like to write a macro which goes through all cells in column and if it finds any formula in cell then it simply ignores this cells and simply 'DO NOTHING'.
I know about HasFormula property in VBA but not really sure it works for cells where I sum two cells simply (for instance, =C4+C5). Here is an example:
'loop (if the cell has formula then loop ignores that cell
i = 1
For i = 5 To 100
If InStr(1, Sheets("Corporate Detailed").Cells(i, "F"), "+") > 0 Then
could be also used---'If Sheets("Corporate Detailed").Cells(i, "G").HasFormula = True Then
Else
'Do some operations
End If
Next i
End Sub

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