entering iferror and left formulas to vba [duplicate] - vba

I want to insert an if statement in a cell through vba which includes double quotes.
Here is my code:
Worksheets("Sheet1").Range("A1").Value = "=IF(Sheet1!B1=0,"",Sheet1!B1)"
Due to double quotes I am having issues with inserting the string. How do I handle double quotes?

I find the easiest way is to double up on the quotes to handle a quote.
Worksheets("Sheet1").Range("A1").Formula = "IF(Sheet1!A1=0,"""",Sheet1!A1)"
Some people like to use CHR(34)*:
Worksheets("Sheet1").Range("A1").Formula = "IF(Sheet1!A1=0," & CHR(34) & CHR(34) & ",Sheet1!A1)"
*Note: CHAR() is used as an Excel cell formula, e.g. writing "=CHAR(34)" in a cell, but for VBA code you use the CHR() function.

Another work-around is to construct a string with a temporary substitute character. Then you can use REPLACE to change each temp character to the double quote. I use tilde as the temporary substitute character.
Here is an example from a project I have been working on. This is a little utility routine to repair a very complicated formula if/when the cell gets stepped on accidentally. It is a difficult formula to enter into a cell, but this little utility fixes it instantly.
Sub RepairFormula()
Dim FormulaString As String
FormulaString = "=MID(CELL(~filename~,$A$1),FIND(~[~,CELL(~filename~,$A$1))+1,FIND(~]~, CELL(~filename~,$A$1))-FIND(~[~,CELL(~filename~,$A$1))-1)"
FormulaString = Replace(FormulaString, Chr(126), Chr(34)) 'this replaces every instance of the tilde with a double quote.
Range("WorkbookFileName").Formula = FormulaString
This is really just a simple programming trick, but it makes entering the formula in your VBA code pretty easy.

All double quotes inside double quotes which suround the string must be changed doubled. As example I had one of json file strings : "delivery": "Standard",
In Vba Editor I changed it into """delivery"": ""Standard""," and everythig works correctly. If you have to insert a lot of similar strings, my proposal first, insert them all between "" , then with VBA editor replace " inside into "". If you will do mistake, VBA editor shows this line in red and you will correct this error.

I have written a small routine which copies formula from a cell to clipboard which one can easily paste in Visual Basic Editor.
Public Sub CopyExcelFormulaInVBAFormat()
Dim strFormula As String
Dim objDataObj As Object
'\Check that single cell is selected!
If Selection.Cells.Count > 1 Then
MsgBox "Select single cell only!", vbCritical
Exit Sub
End If
'Check if we are not on a blank cell!
If Len(ActiveCell.Formula) = 0 Then
MsgBox "No Formula To Copy!", vbCritical
Exit Sub
End If
'Add quotes as required in VBE
strFormula = Chr(34) & Replace(ActiveCell.Formula, Chr(34), Chr(34) & Chr(34)) & Chr(34)
'This is ClsID of MSFORMS Data Object
Set objDataObj = CreateObject("New:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")
objDataObj.SetText strFormula, 1
objDataObj.PutInClipboard
MsgBox "VBA Format formula copied to Clipboard!", vbInformation
Set objDataObj = Nothing
End Sub
It is originally posted on Chandoo.org forums' Vault Section.

In case the comment by gicalle ever dies:
I prefer creating a global variable:
Public Const vbDoubleQuote As String = """" 'represents 1 double quote (")
Public Const vbSingleQuote As String = "'" 'represents 1 single quote (')
and using it like so:
Shell "explorer.exe " & vbDoubleQuote & sPath & vbDoubleQuote, vbNormalFocus

Related

How to use VBA .Formula with row number incrementation? [duplicate]

I want to insert an if statement in a cell through vba which includes double quotes.
Here is my code:
Worksheets("Sheet1").Range("A1").Value = "=IF(Sheet1!B1=0,"",Sheet1!B1)"
Due to double quotes I am having issues with inserting the string. How do I handle double quotes?
I find the easiest way is to double up on the quotes to handle a quote.
Worksheets("Sheet1").Range("A1").Formula = "IF(Sheet1!A1=0,"""",Sheet1!A1)"
Some people like to use CHR(34)*:
Worksheets("Sheet1").Range("A1").Formula = "IF(Sheet1!A1=0," & CHR(34) & CHR(34) & ",Sheet1!A1)"
*Note: CHAR() is used as an Excel cell formula, e.g. writing "=CHAR(34)" in a cell, but for VBA code you use the CHR() function.
Another work-around is to construct a string with a temporary substitute character. Then you can use REPLACE to change each temp character to the double quote. I use tilde as the temporary substitute character.
Here is an example from a project I have been working on. This is a little utility routine to repair a very complicated formula if/when the cell gets stepped on accidentally. It is a difficult formula to enter into a cell, but this little utility fixes it instantly.
Sub RepairFormula()
Dim FormulaString As String
FormulaString = "=MID(CELL(~filename~,$A$1),FIND(~[~,CELL(~filename~,$A$1))+1,FIND(~]~, CELL(~filename~,$A$1))-FIND(~[~,CELL(~filename~,$A$1))-1)"
FormulaString = Replace(FormulaString, Chr(126), Chr(34)) 'this replaces every instance of the tilde with a double quote.
Range("WorkbookFileName").Formula = FormulaString
This is really just a simple programming trick, but it makes entering the formula in your VBA code pretty easy.
All double quotes inside double quotes which suround the string must be changed doubled. As example I had one of json file strings : "delivery": "Standard",
In Vba Editor I changed it into """delivery"": ""Standard""," and everythig works correctly. If you have to insert a lot of similar strings, my proposal first, insert them all between "" , then with VBA editor replace " inside into "". If you will do mistake, VBA editor shows this line in red and you will correct this error.
I have written a small routine which copies formula from a cell to clipboard which one can easily paste in Visual Basic Editor.
Public Sub CopyExcelFormulaInVBAFormat()
Dim strFormula As String
Dim objDataObj As Object
'\Check that single cell is selected!
If Selection.Cells.Count > 1 Then
MsgBox "Select single cell only!", vbCritical
Exit Sub
End If
'Check if we are not on a blank cell!
If Len(ActiveCell.Formula) = 0 Then
MsgBox "No Formula To Copy!", vbCritical
Exit Sub
End If
'Add quotes as required in VBE
strFormula = Chr(34) & Replace(ActiveCell.Formula, Chr(34), Chr(34) & Chr(34)) & Chr(34)
'This is ClsID of MSFORMS Data Object
Set objDataObj = CreateObject("New:{1C3B4210-F441-11CE-B9EA-00AA006B1A69}")
objDataObj.SetText strFormula, 1
objDataObj.PutInClipboard
MsgBox "VBA Format formula copied to Clipboard!", vbInformation
Set objDataObj = Nothing
End Sub
It is originally posted on Chandoo.org forums' Vault Section.
In case the comment by gicalle ever dies:
I prefer creating a global variable:
Public Const vbDoubleQuote As String = """" 'represents 1 double quote (")
Public Const vbSingleQuote As String = "'" 'represents 1 single quote (')
and using it like so:
Shell "explorer.exe " & vbDoubleQuote & sPath & vbDoubleQuote, vbNormalFocus

.range.Formula of a Concatenate() to a server path

I'm trying to fill in a cell with the =CONCATENATE() formula which gave me errors,
strformula = "=CONCATENATE("\\SERVER\PATH\DIR\";$A5;".pdf")"
I tried to fix this with the incode concatenate & method
but I somehow have an error with the Sub
"Method or data member not found"
Any ideas?
Sub Fillcells()
Dim pthstr As String
Dim strformula As String
With sheetNAME
pthstr = "\\SERVER\PATH\DIR"
strformula = "=CONCATENATE(" & pthstr & ";$A5;\" \ .pdf \ ")"
.Range("N5:N5").Formula = strformula
'.Range("N5", "N" & GetLastRow(sheetNAME)).FillDown
End With
End Sub
You have a couple issues with how you're handling your string text. I think this will work as a formula for you or at least allow you to avoid errors.
strformula = "=CONCATENATE(""" & pthstr & """,$A5,""\ .pdf \ "")"
Note that for quotes within the formula, you have to use 2x double quotes. And if this is the end of your quote, you;ll have THREE sets, followed by an & sign.
However, I'm not sure concatenate is really what you want. You might just consider typing ="\\SERVER\PATH\DIR\"&A5&".PDF"
There's almost no reason one should ever use Concatenate when compared to alternative functions such as textjoin or Concat. This article explains. Good luck.

How to use vlookup (the formula) to search for string in VBA

Hi everyone I have a problem with VBA when I try to use vlookup formula like this:
Range("H21").Formula = "=VLOOKUP("cleared",'mortgage'!A2:F12,4,FALSE)"
it keeps telling me the part "cleared" is an syntax error. Can someone tell me how to deal with that? Thank you in advance.
double the quotes:
Range("H21").Formula = "=VLOOKUP(""cleared"",'mortgage'!A2:F12,4,FALSE)"
Your VBE thinks the word cleared is not part of the string as you've terminated it with double-quotes beforehand. You then appear to be starting a new string immediately after the word cleared.
To use double quotes (aka speech-marks) within a string, you'll need to double them up like so:
Range("H21").Formula = "=VLOOKUP(""cleared"",'mortgage'!A2:F12,4,FALSE)"
Use single quotes around cleared (DOES NOT WORK):
Range("H21").Formula = "=VLOOKUP('cleared','mortgage'!A2:F12,4,FALSE)"
EDIT : Correction made by OP :
Excel uses single quotes only on the sheet name, not to denote a string literal
Or another option:
Write the working formula in Excel.
Select the cell with the
formula.
Run the following code:
Sub TestMe
debug.print selection.formula
End Sub
Check the immediate window - that's the formula you are using in Excel.
If you want useful formula, that you can actually copy+paste in your VBA code, use this:
Option Explicit
Public Sub PrintMeUsefulFormula()
Dim strFormula As String
Dim strParenth As String
strParenth = """"
strFormula = Selection.Formula
strFormula = Replace(strFormula, """", """""")
strFormula = strParenth & strFormula & strParenth
Debug.Print strFormula
End Sub
Check the immediate window.

Write a VLOOKUP as a string in a cell with dynamic path retrieved through GetoOpenfilename

I am trying to write a VLOOKUP in a cell as a string, with VBA. This means that I do not want the result to appear in the cell as a value, but I want the whole VLOOKUP expression instead (For this example : "VLOOKUP(C6,'[path_to_file.xlsm]OTD Table!$B:$F,4,0)"). The challenge is that the range argument of the VLOOKUP is a concatenation of a path (path_to_file.xlsm) that the user selects with a GetOpenFilename, and a string that specifies the tab in which the lookup table is located ("OTD Table!$B:$F,4,0").
The issue I am getting is very interesting :
When I print my expression in a Msgbox, the expression appears correctly. However, when I write it in a cell, the path mysteriously appears incorrectly.
Sub macro()
dim data_file_new as String
data_file_new = CStr(Application.GetOpenFilename(FileFilter:="Excel Workbooks (*.xls*),*.xls*", Title:="Select new data file")) ' The user selects the file
str_ = "=VLOOKUP(C6," & "'[" & data_file_new & "]OTD Table!$B:$F,4,0)" ' This will display the expression correctly
cells(1,10)="=VLOOKUP(C6," & "'[" & data_file_new & "]OTD Table!$B:$F,4,0)"' This will not display the same thing as in the messagebox above
end Sub
I hope one of you guys can make sens of this !
Because you're dropping a formula into a cell that you want to display as straight text, you have to be explicit with Excel and tag the text string to prevent interpreting it as a formula. The simplest way to do this is pre-pend the string with a single-quote "'".
Sub macro()
Dim data_file_new, str_ As String
str_ = "'=VLOOKUP(C6,'["
data_file_new = CStr(Application.GetOpenFilename(FileFilter:="Excel Workbooks (*.xls*),*.xls*", Title:="Select new data file")) ' The user selects the file
str_ = str_ & data_file_new & "]OTD Table!$B:$F,4,0)" ' This will display the expression correctly
ActiveSheet.Cells(1, 10).Value = str_
End Sub
Yeah either you'll need to set the string to add a single quote, or you'll need to change the numberformat of the cell to text (Cells(1,10).NumberFormat = "#")
Either of those should work.

Remove paragraph mark from string

I have a macro that finds all of the 'Heading 1' styles within my document and lists them in a ComboBox on a UserForm.
My problem is that the Find routine I am using is also selecting the paragraph mark (ΒΆ) after the text I wish to copy, and that is being displayed in the ComboBox.
How can I remove this from the string? I've tried useing replace(), replacing vbCrLf, vbCr, vbLf, vbNewLine, ^p, v, Chr(244) and Asc(244) with "", but nothing has succeeeded. For example -
sanitizedText = Replace(Selection.Text, "^v", "")
Can anyone please help with this problem? Thanks.
Here is how my form looks -
You should use ChrW$() for unicode characters:
sanitizedText = Replace(Selection.Text, ChrW$(244), "")
Or, if the paragraph mark is always at the end maybe you can just remove the last character using
myString = Left(myString, Len(myString) - 1)
I used sanitizedText = Replace(Selection.Text, Chr(13), "") successfully; 13 is the ASCII value for 'carriage return'.
This tiny script replaces, in a piece of text selected in the document (i.e. marked using the cursor) hyphens that are at the beginning of a line. It replaces them by an improvised bullet point: (o)
The script searches for occurances of "Paragraph mark followed by hyphen".
I had a similar problem as in the question above, as I was sure paragraph marks should be 'Chr(13) & Chr(10)', which is equal 'VbCrLF', which is equal 'Carriage Return, Line Feed'. However, 'Chr(13) & Chr(10)' were wrong. The naked Chr(13) did the job.
Sub MakeAppFormListPoints()
'Replace list hyphens by (o)
Dim myRange As Range
Set myRange = Selection.Range 'What has been marked with the cursor
Debug.Print myRange ' Just for monitoring what it does
myRange = replace(myRange, Chr(13) & "-", Chr(13) & "(o)")
Debug.Print myRange ' Just for monitoring what it does
End Sub
(I use this for adjusting text written in Word to the insanely restricted character set of the official application form for the European Union Erasmus+ programme to promote lifelong learning activities. Well, I learned something.)