Add =IFERROR function to formulas - vba

I'm trying to add =IFERROR function to Excel formulas. Example original formula in active cell: =A1/B3, example new formula: =IFERROR(A1/B3;0). However it results in runtime error. The formula shown in the message box appears to be correct.
I've tested the same code for adding parentheses to formulas with the variables: First_part = "=(" and Last_Part = ")", which worked fine. I've also tested the same code with IF function using the variables:
First_part = "=IF(F1=2;" and Last_Part = ";0)", which also resulted in runtime error.
Sub Adding_IFERROR()
Dim Cell_Content As String
Dim First_Part As String
Dim Last_Part As String
Dim New_Cell_Content As String
First_Part = "=IFERROR("
Last_Part = ";0)"
'Remove the initial "=" sign from original formula
Cell_Content = ActiveCell.Formula
Cell_Content = Right(Cell_Content, Len(Cell_Content) - 1)
'Writing new formula
New_Cell_Content = First_Part & Cell_Content & Last_Part
MsgBox New_Cell_Content, vbOKOnly
ActiveCell.Formula = New_Cell_Content
End Sub
Is there any obvious reason to why it doesn't work?

You need to use commas instead of semicolons, when creating formulas by VBA.
So, change this:
Last_Part = ";0)"
to this:
Last_Part = ",0)"

After spending hours yesterday, I found the solution 5 seconds after posting the question.
Solution:
Last_Part = ",0"
I use semicolon ";" as separator in excel, but when inserting from VBA I had to use comma ",".

Related

How to shorten VBA code using repeated SUMIFS function?

I have written up a number of SUMIFS in VBA based on the change of a value in cells
E.g. Cell A23 is a drop down menu with Total and UK
If A23 = "Total" Then
Result.Range("A24").Value = WorkSheetFunction.Sumifs(Range(B:B)),
Range(C:C)), "Year",
Range(D:D)), "Group")
If A23 = "UK" Then
Result.Range("A24").Value = WorkSheetFunction.Sumifs(Range(B:B)),
Range(C:C)), "Year",
Range(D:D)), "Group",
Range(E:E)), "UK")
Based on the example above, the second code is a repeat of the first code but with an additional range included to pick up "UK"
Instead of constantly rewriting it is there a way I can shortern the code so I can simply concatenate any additional range I want to include?
So ideally I could have something like:
Test = Result.Range("A24").Value = WorkSheetFunction.Sumifs(Range(B:B)),
Range(C:C)), "Year",
Range(D:D)), "Group"
If A23 = Total Then
A24 = Test)
If A23 = UK Then
A24 = Test &, Range(E:E), "UK")
Is this possible and if so how can I do it?
Could you enter the actual function in the cells, rather than do the worksheetfunction calculation in the vba? (doing worksheetfunction calculations won't actually enter the formula in the cells, just return the output value)
Something like this maybe:
Dim strFormula as String
strFormula = "=SUMIFS(B:B, C:C, ""Year"", D:D, ""Group"")"
'Thats the basic formula
If Result.Range("A23").Value = "UK" Then
strFormula = replace(strFormula, ")", "E:E, ""UK"")")
'that replaces the end bracket with the extra condition
End If
Result.Range("A4").FormulaA1 = strFormula
(this answer posted mainly in response to that second comment with the actual code included - although it looks like the actual operation you're doing is a bit different?)
So, as I said you need to simplify that code out a bit by saving the separate parts in variables
Dim strFormula as String
Dim rngLIC as Range
Dim rngRegion as Range
Dim rngYear as Range
Set rngLIC = Range(rngHeaders.Find(LIC) , rngHeaders.Find(LIC).End(xlDown))
Set rngRegion = Range(rngHeaders.Find(Year), rngHeaders.Find(Year).End(xlDown))
Set rngYear = Range(rngHeaders.Find(Year), rngHeaders.Find(Year).End(xlDown))
'and I think you'll need to add others for the extra bit you wanted to fix, but you get the pattern
strFormula = "=SUMIFS(" & _
rngLIC.Address(xlA1) & "," & _
rngRegion.Address(xlA1) & ", A23," & _
rngYear.Address(xlA1) & ", ""Year 0"")"
'Then add the replace bit I detailed above if necessary to add bits to the formula
That code should hopefully do xsactly the same as the code snippet you put in the comment. Does that help? (please vote up if it does because I'm trying to build my reputation!!)

Removing All Spaces in String

I created a macro for removing all whitespace in a string, specifically an email address. However it only removes about 95% of the whitespace, and leaves a few.
My code:
Sub NoSpaces()
Dim w As Range
For Each w In Selection.Cells
w = Replace(w, " ", "")
Next
End Sub
Things I have tried to solve the issue include:
~ Confirmed the spaces are indeed spaces with the Code function, it is character 32 (space)
~ Used a substitute macro in conjuction with the replace macro
~ Have additional macro utilizing Trim function to remove leading and trailing whitespace
~ Made a separate macro to test for non-breaking spaces (character 160)
~ Used the Find and Replace feature to search and replace spaces with nothing. Confirmed working.
I only have one cell selected when I run the macro. It selects and goes through all the cells because of the Selection.Cells part of the code.
A few examples:
1 STAR MOVING # ATT.NET
322 TRUCKING#GMAIL.COM
ALEZZZZ#AOL. COM.
These just contain regular whitespace, but are skipped over.
Just use a regular expression:
'Add a reference to Microsoft VBScript Regular Expressions 5.5
Public Function RemoveWhiteSpace(target As String) As String
With New RegExp
.Pattern = "\s"
.MultiLine = True
.Global = True
RemoveWhiteSpace = .Replace(target, vbNullString)
End With
End Function
Call it like this:
Sub NoSpaces()
Dim w As Range
For Each w In Selection.Cells
w.Value = RemoveWhiteSpace(w.Value)
Next
End Sub
Try this:
Sub NoSpaces()
Selection.Replace " ", ""
End Sub
Use "Substitute"
Example...
=SUBSTITUTE(C1:C18," ","")
Because you assume that Selection.Cells includes all cells on the sheet.
Cells.Replace " ", ""
And to add to the excellent advice from all the great contributors, try the
TRIM or LTRIM, or RTRIM and you can read more about these functions here:
https://msdn.microsoft.com/en-us/library/office/gg278916.aspx
Now this does not remove embedded spaces (spaces in between the letters) but it will remove any leading and trailing spaces.
Hope this helps.
Space Problem with Excel
ok, the only way i see this two types of space is by converting their Ascii code value of which I do it here
now to explain this function i made, it will just filter the string character by character checking if its equal to the two types of space i mentioned. if not it will concatenate that character into the string which will be the final value after the loop. hope this helps. Thanks.
Function spaceremove(strs) As String
Dim str As String
Dim nstr As String
Dim sstr As String
Dim x As Integer
str = strs
For x = 1 To VBA.Len(str)
sstr = Left(Mid(str, x), 1)
If sstr = " " Or sstr = " " Then
Else
nstr = nstr & "" & sstr
End If
Next x
spaceremove = nstr
End Function
I copied a HTML table with data and pasted in excel but the cells were filled with unwanted space and all methods posted here didn't work so I debugged and I discovered that it wasn't actually space chars (ASCII 32) it was Non-breaking space) (ASCII 160) or HTML
So to make it work with that Non-breaking space char I did this:
Sub NoSpaces()
Dim w As Range
For Each w In Selection.Cells
w.Value = Replace(w.Value, " ", vbNullString)
w.Value = Replace(w.Value, Chr(160), vbNullString)
Next
End Sub

Function that returns a string representing a worksheet row

I'm trying to create a function (named CreateRowRange) that will take a string having the form "$A$5" and produce a string having the form "A5:M5". Similarly, if I call the function with "$A$14", it will return "A14:M14". I have an Excel spreadsheet with data in columns "A" through "M". I found a similar post on Stack Overflow (Concatenating Variables Into String to be Set to a Range in VBA), but it seems overly complicated. The code written thus far for the function is:
Function CreateRowRange(CellAddress) As String
CreateRowRange = Range(CellAddress).Row
End Function
This should return what you want:
Function CreateRowRange(CellAddress) As String
CreateRowRange = Range(Range(CellAddress),Range("M" & Range(CellAddress).Row)).Address(False,False)
End Function
Ok, try this:
Function CreateRowRange(CellAddress as String) as String
CreateRowRange = Replace(CellAddress, "$", "")
CreateRowRange = CreateRowRange & ":" & Replace(CreateRowRange, "A", "M")
End Function
Excel already has built in properties and methods to modify ranges. If you're going to use it like
Range(CreateRowRange("$A$14")).Value = "X"
then you can achieve the same thing with
Range("$A$14").Resize(1,13).Value = "X"
If you're building a formula like
ActiveCell.Formula = "=SUM(" & CreateRowRange("$A$14") & ")"
then you can achieve the same thing with
ActiveCell.Formula = "=SUM(" & Range("A14").Resize(1,13).Address(0,0) & ")"
The 0,0 part makes the address relateive - no dollar signs

VBA Excel: Concatenate a range of cells

I am trying to concatenate a range of cells along a single row. This group of cells has a defined start but a variable end. I tried doing this, but it didn't work. I'm still learning the Syntax of VBA but I haven't seen anything that says this WON'T work. Any help is appreciated.
Dim hexVal As String
For i = 4 To N + 3
Cells(3, i) = Application.WorksheetFunction.Dec2Hex(Cells(2, i), 2) & " "
Next i
hexVal = CONCATENATE(Range(Cells(3,i),Cells(3,N+3))
End Sub
You do not need Concatenate(), but using & instead:
for i = 4 to N + 3
hexVal = hexVal & cells(3,i)
next i
That is in case you are just concatenate the strings and you do know the range needs to be concatenate.
HEre's your problem:
CONCATENATE(Range(Cells(3,i),Cells(3,N+3))
The Cells method returns a range object, the default property of which is the .Value property. So, this is equivalent to:
CONCATENATE(Range(Cells(3,i).Value,Cells(3,N+3).Value)
As such, it will ALWAYS FAIL unless those cells contain a valid address string.
Solution ... just use the built-in concatenator
hexVal = Range(Cells(3,i) & Cells(3,N+3))
Or:
hexVal = CONCATENATE(Range(Cells(3,i).Value,Cells(3,N+3).Value))

Get Excel cell background color hex value

I would like to obtain the background color of a cell in an Excel sheet using a UDF formula or VBA.
I found this UDF:
Public Function BColor(r As Range) As Long
BColor = r(1).Interior.ColorIndex
End Function
It can be used like this in a cell: =BColor(A1)
I'm not familiar with VBA, this returns some long value and I wonder if it is possible to obtain the hex value directly. Thank you!
try this
Function HexCode(Cell As Range) As String
HexCode = Right("000000" & Hex(Cell.Interior.Color), 6)
End Function
I tried the above code, but it returned a BGR value (as suggested)
However, this code returns a RGB Hex value.
I just can't get it to auto update.
Public Function HexCodeRGB(cell As Range) As String
HexCodeBGR = Right("000000" & Hex(cell.Interior.Color), 6)
HexCodeRGB = Right(HexCodeBGR, 2) & Mid(HexCodeBGR, 3, 2) & Left(HexCodeBGR, 2)
End Function
Good luck
Based on the best voted answer, here is an example of a real case, my case.
I supply it as a macro and a screenshots. I hope this can help someone out.
The VBA macro is simple but I'll paste it here. If you take a look at the attachment you will see that I have duplicated that column and cleared the color names in Spanish and titled the column "color", the I did run this macro:
Sub printHEXBGColor()
Set r = Range("myRange")
Dim HEXcolor As String
Dim i As Long
For i = 1 To r.Rows.Count
r.Cells(i, 1).Activate
HEXcolor = "#" + Right("000000" & Hex(ActiveCell.Interior.Color), 6)
ActiveCell = HEXcolor
Next i
End Sub
Screenshot of the result