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
I need to build a large string (json) in VBA with quotes in it.
I tried this approach:
Dim payload As String
payload = ""
payload = payload & CHR(34) & {"timeframeId":13,"startDate":"2021-05-31 00:00:00.000","endDate":"2021-05-31 00:00:00.000","peopleList":[{"id":123}], & CHR(34)
...more lines building string
But the Excel IDE for VBA complains of a syntax error - presumeably to do with the quoted strings?
Do I need to add CHR(34) before the opening and after closing " of each?
Al Grant!
Chr(39) or " double quote char is the text qualifier to VBA, so you need to do an ajustment to use in the strings.
I presume you have this value anywhere in the worksheet.
So the common way to do this is set the range and use replace to another char, and after all back to chr(39).
If you what to input in hardcode, you will need to concatenate chr(39) with everytime a doublequote appears, or use ""
But the easiest way is to replace find and replace (CTRL+H) to another char, and continue to develop like you was doing
Dim payload As String
payload = payload & Chr(34) & Replace("{'timeframeId':13,'startDate':'2021-05-31 00:00:00.000','endDate':'2021-05-31 00:00:00.000','peopleList':[{'id':123}],", Chr(39), Chr(34)) & Chr(34)
Debug.Print payload
Result:
"{"timeframeId":13,"startDate":"2021-05-31 00:00:00.000","endDate":"2021-05-31 00:00:00.000","peopleList":[{"id":123}],"
I'm trying to run this code:
Set Lrs = db.OpenRecordset("Select [LastName]" & _
"From ['Chromebook Registration Form]" & _
"Where [InventoryNumber] = dbInventoryNumber ")
Where "dbInventoryNumber" is a double variable. The field [InventoryNumber] takes a double, but when I run this I get a 3061 Run-time error. Too few arguments. Expected 1.
I know how to pass string variables as parameters, but how do I do it for doubles?
Thanks!
Although the [ ]s will allow the SQL to evaluate, should include space at end of each continued line so SQL string doesn't run together when compiled. Pass double variable same way as string except don't use apostrophe delimiters. (Date/time field parameters use # delimiter.) Don't put variables within quote marks, concatenate them. Remove apostrophe in front of source (assuming this is not really in source name - advise no spaces nor punctuation/special characters in naming convention). Source name that includes word "Form" sounds like name of a form. Source must be a table or query.
Set Lrs = db.OpenRecordset("Select [LastName] " & _
"From [Chromebook Registration Form] " & _
"Where [InventoryNumber] = " & dbInventoryNumber)
I am trying to pass 3 textboxes into a different form via parsing the string. I am getting a run time error 13.
Private Sub txtFullName_Click()
Const cstrForm As String = "frmInputInfo"
DoCmd.OpenForm "frmInputInfo", acFormAdd, , , acDialog, _
Me.txtFullName & "|" & Me.PATS_Job_Opening_ID & "|" & Me.NYCAPS_JobID
End Sub
Private Sub Form_Load()
varSplitString = Split(Me.OpenArgs, "|")
Me.[FullName].Value = varSplitString(0)
Me.[PATS Job Opening ID].Value = varSplitString(1)
Me.[NYCAPS_JobID].Value = varSplitString(2)
End Sub
and them on the form load I typed
Any help will be appreciated
You have to be extremely attentive with all those commas in the DoCmd.OpenForm options list. It's just way too darn easy to cause a misalignment between what you and Access think about which values apply to which options.
In your case you intend to pass a string, Me.txtFullName & "|" & Me.PATS_Job_Opening_ID & "|" & Me.NYCAPS_JobID, to OpenArgs. Unfortunately you omitted a comma, so Access thinks you're feeding it a value for WindowMode, which is supposed to be a number. Therefore, error 13: "type mismatch"!
Do it this way and you eliminate any confusion about which value goes with which option.
Dim strArgs As String
strArgs = Me.txtFullName & "|" & Me.PATS_Job_Opening_ID & "|" & Me.NYCAPS_JobID
Debug.Print strArgs ' make sure you got what you expect '
DoCmd.OpenForm FormName:="frmInputInfo", _
DataMode:=acFormAdd, _
WindowMode:=acDialog, _
OpenArgs:=strArgs
Also in the form event, make sure you got something for OpenArgs before you attempt to Split it. As it stands now, if the form is ever opened without supplying OpenArgs, your code will essentially attempt Split(Null, "|") and that will trigger a different error.
You can test before split like this:
If Len(Me.OpenArgs) > 0 Then
' do your split thing here '
End If
How do I get around the limitation VBA have of not allowing spaces in file path when using the FileSystemObject?
Here is my code:
from= "C:\Users\MyAccount\Desktop\a.txt"
to= "C:\Users\MyAccount\Desktop\Folder Name With Spaces\b.txt"
Dim fso As New FileSystemObject
Set fso = CreateObject("Scripting.FileSystemObject")
fso.CopyFile from, to
I have already tried the trick with adding " before any spaces, it doesn't work. The "Bad FileName or Number" error actually pops up.
I have also tried to replace any spaces with %20, which also does not work.
To clarify, I don't know the path beforehand, it is entered by the user.
There's no restriction around having spaces in filenames or paths, either in VBA or when using the FSO. You must have some other problem.
For example I don't think FSO will create a destination folder if it doesn't already exist.
Also: you don't need to use Createobject if you Dim ... As New ...: your object is created in the Dim statement.
My solution to the same issue:
Dim folderPath As String
folderPath = "D:\MyData\BackUp\capdat\City Name"
If Len(Dir$((folderPath & "\OLDData" & Format(Date, "-ddmmyyyy") & ".accdb"))) > 0 Then
Kill (folderPath & "\OLDData" & Format(Date, "-ddmmyyyy") & ".accdb"
Else
Do something
End if
its a while since I did any VBA but I think you need to enclose your strings in quotes to negate the spaces in the paths, so does this work:
fso.CopyFile """" + from + """", """" + to+ """"
EDIT:
This site suggested this routine:
Private Function GetQuotedArgument(ByVal argument As String) As String
Const Quote As String = """"
Return String.Format("{0}{1}{0}", Quote, argument)
End Function
giving:
fso.CopyFile GetQuotedArgument(from), GetQuotedArgument(to)
Failing that you'll have to resort to short forms of the file names... Microsoft article on doing that here, not sure if it applies to VBA though
I want to create a classic asp (vbscript) function that replaces all 'returns' that occur between double quotes.
The input string is 'csv' like:
ID;Text;Number
1;some text;20
2;"some text with unwanted return
";30
3;some text again;40
I want to split the string on chr(13) (returns) to create single rows in an array. It works well, except for the unwanted chr(13) that is contained in the text of id 2.
I hope someone could help.
Fundamentally, this is going to be difficult to do as you won't be able to tell whether the carriage return is a valid one or not. Clearly the ones after 20 and 30 are valid.
An approach I would would be to scan through each line in the file and count the commas that occur. If it's less than 3, then append the next line and use the concatenated string. (This of course assumes your CSV structure is consistent and fixed).
What I would really be asking here is why is the CSV like this in the first place? The routine that populates this should really be the one stripping the the CRs out.
Think of a CSV file like a very crude database or spreadsheet. When cosidering the above file, it is clear that the 'Database'/'Spreadsheet' is corrupt.
If the program that generates this is correupting it, then what extent should the reading application goto to correct these defects? I'm not sure that Excel or SQL Server (for example) would go to great lengths to correct a corrupt data source.
Your text file is just like a CSV file but with semicolons not commas. Use ADO to grab the data and it will handle the line breaks in fields.
Specifically (In ASP VBScript):
On Error Resume Next
Const adOpenStatic = 3
Const adLockOptimistic = 3
Const adCmdText = &H0001
Set objConnection = Server.CreateObject("ADODB.Connection")
Set objRecordSet = Server.CreateObject("ADODB.Recordset")
strPathtoTextFile = server.mappath(".") 'Path to your text file
objConnection.Open "Provider=Microsoft.Jet.OLEDB.4.0;" & _
"Data Source=" & strPathtoTextFile & ";" & _
"Extended Properties=""text;HDR=YES;FMT=Delimited"""
objRecordset.Open "SELECT * FROM test.txt", _
objConnection, adOpenStatic, adLockOptimistic, adCmdText
Do Until objRecordset.EOF
Response.Write "ID: " & objRecordset.Fields.Item("ID") & "<br>"
Response.Write "Text: " & objRecordset.Fields.Item("Text") & "<br>"
Response.Write "Number: " & objRecordset.Fields.Item("Number") & "<br>"
objRecordset.MoveNext
Loop
Code sample is modified from Microsofts' Much ADO About Text Files.
This script assumes your data text file is in the same directory as it (the asp file). It also needs a schema.ini file in the same directory as your data text file with the data:
[test.txt]
Format=Delimited(;)
Change text.txt in both code samples above to the name of your text file.
If the unwanted CRLF always occurs inside a text field (inside double quotes), it would not be very difficult to use a regular expression to remove these. Vbscript has a regex engine to its disposal: http://authors.aspalliance.com/brettb/VBScriptRegularExpressions.asp
It all depends ofcourse on how familiar you are with Regular Expressions. I couldn't think of the proper syntax off the top of my head, but this is probably quite easy to figure out.
The solution is pretty easy:
str = "Some text..." & chr(13)
str = REPLACE(str,VbCrlf,"")
The secret is use VbCrlf. For me I use a simple function for solve the problem and add this in my framework.
FUNCTION performStringTreatmentRemoveNewLineChar(byval str)
IF isNull(str) THEN
str = ""
END IF
str = REPLACE(str,VbCrlf,"")
performStringTreatmentRemoveNewLineChar = TRIM(str)
END FUNCTION
Of course this will remove all new lines character from this string. Use carrefully.