IF statement with RC in vba gives compile error, why? - vba

I am currently working on a small VBA code that needs to compare a piece of string. If I would type this directly into excel I would do following:
=IF(C14 = "ABC",1,0)
Now, since this is a VBA code, it needs to do this as a relative reference. Instead it would look something like this:
=IF(RC[-5] = "ABC",1,0)
Problem: Now, the latter IF statement gives a compile error - why so?
If I where to type in
=IF(RC[-5] = 2,1,0)
This does not give any compile error. So it appears that the String comparisment gives me problems.

For vba code try this
ActiveCell.FormulaR1C1 = "=IF(RC[-5]=""ABC"",1,0)"
Followup from comments.
Howcome the double "" is needed? – SteewDK 3 mins ago
We need the extra " to encompass the double quotes to pass it as a string. You could use Chr(34) as well. For example
ActiveCell.FormulaR1C1 = "=IF(RC[-5]=" & Chr(34) & "ABC" & Chr(34) & ",1,0)"
BTW if you do not want to use a formula then you can use OFFSET as well
For example
If ActiveCell.Offset(0,-5).Value = "ABC" Then _
ActiveCell.Value = 1 Else ActiveCell.Value = 0

Related

VBA dynamic dates inside an API URL

I have an API that I want to update dynamically so that the user can enter a start date and an end date on a spreadsheet and my macro will pull back data for that particular date range.
The issue I'm having is that within the API URL the StartDate and EndDate parameters must be in the format yyyy-mm-dd as a string.
I've tried URL = "https:// ...&StartDate = Format(Date(),"yyyy-mm-dd") & EndDate=Format(Date(),"yyyy-mm-dd")&..." (the ... is for the things before and after the URL).
An example of the type of URL I'm looking at is:
https://www.googleapis.com/analytics/v3/data/ga?ids=ga:12345&startdate=2008-10-01&end-date=2008-10-31&metrics=ga:sessions,ga:bounces
I've also played around with adding in extra quotes within the URL string but I can't seem to get it to work.
I keep getting told that the dates aren't being recognised and therefore I can only get the code to run if I hardcode dates.
Any suggestions?
I noticed a few issues in the code posted. The & is the concatenation operator in VBA. You need to enclose that in "" to make sure you are returning the ampersand as a string, and not joining strings together.
I've added some sample code which hopefully illustrates the idea and get's you back up and running. The code should print out True if the createdURL and testURL are equal, or False if not.
Code
Option Explicit
Public Sub FormatExample()
'This is the example provided
Dim testURL As String
testURL = "https://www.googleapis.com/analytics/v3/data/ga?ids=ga:12345&" & _
"startdate=2008-10-01&end-date=2008-10-31&metrics=ga:sessions,ga:bounces"
'This is a built string example
Dim createdURL As String
createdURL = "https://www.googleapis.com/analytics/v3/data/ga?ids=ga:12345" & _
"&startdate=" & Format(#10/1/2008#, "yyyy-mm-dd") & _
"&end-date=" & Format(#10/31/2008#, "yyyy-mm-dd") & _
"&metrics=ga:sessions,ga:bounces"
'Print out if they are equal
Debug.Print createdURL = testURL
End Sub

add formula in vba - syntax error

im trying to record a macro. my formula in excel is:
=IF(AND(OR(B2={"1","2","3","4","5","6","7","8","9","10","11","12","13","14","15 ","16 "}),OR(J2={"Q1","Q2","Q3","Q4"})),CONCATENATE(J2," ",IF(K2="p","pre",""),"-"," ",IF(A2="",0,A2)),"")
(this formula basically changes the names of my product according to quarter and type, while taking into consideration previous quarters )
note: once i record it. it looks like this in vba:
Selection.FormulaR1C1 = _
"=IF(AND(OR(RC[-6]={""1"",""2"",""3"",""4"",""5"",""6"",""7"",""8"",""9"",""10"",""11"",""12"",""13"",""14"",""15 "",""16 ""}),OR(RC[2]={""Q1"",""Q2"",""Q3"",""Q4""})),CONCATENATE(RC[2],"" "",IF(RC[3]=""p"",""pre"",""""),""-"","" "",IF("& _
"""",0,RC[-7])),"""")"
and yet, it gives me a syntax error...whats wrong?!
thank you
IF(A2="",0,A2)),"") Is being converted to IF(""",0,RC[-7])),"""")
Assuming that If your original formula is in Range("H2")
"=IF(AND(OR(RC[-6]={""1"",""2"",""3"",""4"",""5"",""6"",""7"",""8"",""9"",""10"",""11"",""12"",""13"",""14"",""15 "",""16 ""}),OR(RC[2]={""Q1"",""Q2"",""Q3"",""Q4""})),CONCATENATE(RC[2],"" "",IF(RC[3]=""p"",""pre"",""""),""-"","" "",IF(RC[-7]="""",0,RC[-7])),"""")"
I don't see the need to surround number with quotes when using formula contants
"=IF(AND(OR(RC[-6]={1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,16}),OR(RC[2]={""Q1"",""Q2"",""Q3"",""Q4""})),CONCATENATE(RC[2],"" "",IF(RC[3]=""p"",""pre"",""""),""-"","" "",IF(RC[-7]="""",0,RC[-7])),"""")"
Don't start a line continuations in the middle of a double escape pattern """". I prefer to place them between statements when possible
The easiest way to convert a formula to R1C1 notation is to use the Immediate Window
?Chr(34) & Replace(Range("H2").FormulaR1C1,chr(34),Chr(34) & Chr(34)) & Chr(34)
Build and test your strings in the Immediate Window when possible. It will complain when it is wrong
You can even use create variables in the Immediate Window when writing concatenations
The only thing that's wrong is the "& _ part. It should be replaced by RC[-7]=. See the corrected line below.
Selection.FormulaR1C1 = _
"=IF(AND(OR(RC[-6]={""1"",""2"",""3"",""4"",""5"",""6"",""7"",""8"",""9"",""10"",""11"",""12"",""13"",""14"",""15 "",""16 ""}), OR(RC[2]={""Q1"",""Q2"",""Q3"",""Q4""})), CONCATENATE(RC[2],"" "",IF(RC[3]=""p"",""pre"",""""),""-"","" "",IF(RC[-7]="""",0,RC[-7])),"""")"

Decimal Confusion in VBA

I run different scripts using VBA on my German computer with an English Excel 2013 version installed on it. My local decimal settings are set to be international, e.g. 123123 is displayed as 123,123.00.
However, when I program with VBA, the decimal changes.
For example:
sub decimal_problem()
dim sDecSep as string
dim sThSep as string
sDecSep = Application.International(xlDecimalSeparator) ' sDecSep = "."
sThSep = Application.International(xlThousandsSeparator) ' sThSep = ","
Fmt= "#" & sThSep & "##0" & sDecSep & "00"
'Fmt looks like "#,##0.00" which is what I want
Msgbox(Format(123123,Fmt)) 'Fmt="#,##0.00"
end sub
The number in the Msgbox is 123.123,00 which is the German number format and definitely not the format I specified before.
When I change the format in a Spreadsheet I get the correct separators (e.g. "#,##0.00" returns 123,123.00).
Do you have a solution for that issue?
As I need to calculate with the formatted number, I try to avoid to change the number to a string and use the replace function.
Thanks for the help!
The code you mentioned above is showing the output you wanted that is 123,123.00 and not 123.123,00.
Also as soon as you will assign this value to a range in a sheet this Text value will get converted to numeric automatically. for ex - thisworkbook.sheets(1).range("a1").value = Format(123123, Fmt)--This will assign cell a1 walue as 123,123.00 which will be in numeric
please let me know if I have not understood your scenario.

MS Access VBA Dlookup on Yes/No field

I can't for the life of me work out what is wrong with this, but I'm not an Access/VBA developer normally..
I have a database table with about 20 fields, one of which is a Yes/No field. I want to extract the Yes/No value using DLookup, however am receiving the following error:
Run-time error '3075':
Syntax error (missing operator) in query expression 'Enabled'.
The code I am using it:
MsgBox (DLookup("Enabled", "Numbers", "ID = " & Me.cbxNumber.Value & ""))
Enabled is a Yes/No field
ID is a String field.
The above DLookup works absolutely fine for returning String values for other fields, so the last parameter with the search query, and the table field, should be fine. It is simply complaining about the return field ('Enabled') thinking it is a query.
The MsgBox element is also irrelevant, as I have tried assigning the result to an Integer and to a Boolean, and it's not complaining of a type mismatch which I would expect if this were the problematic part.
Any thoughts?
You stated that ID is a string field. If that is the case, try changing the DLookup to...
DLookup("[Enabled]", "Numbers", "ID = " & Chr(34) & Me.cbxNumber.Value & Chr(34))
If ID is a Long, then use this string...
DLookup("[Enabled]", "Numbers", "ID = " & Me.cbxNumber.Value)
Your code works fine for me:
Table:
Form:
Code:
Private Sub Command30_Click()
MsgBox (DLookup("Enabled", "Numbers", "ID = " & Me.cbxNumber.Value & ""))
End Sub
The messagebox displays 0 or -1 as required. Things to check:
Is your code in the forms module? Otherwise Me.cbxNumber.Value won't return anything.
What do you get if you run
debug.print Me.cbxNumber
from the OnClick of a button on the form?

How to display value from cell in vba code?

Row_No = 5
MsgBox Range.("A & Row_No").value
i have above code but it gives me error 1004..please help me with this.
Just try this
MsgBox Range.("A" & Row_No).Value
or this
MsgBox Range.("A" & Row_No).Text
or this
MsgBox Cells(1,"C")
Problem with the code you used is nothing but placing of & and " in wrong place.
Hope this helps.
When doing concatenation, keep in mind that strings will be in quotes and variables will not -- think of the quotes as telling the compiler to interpret what is between them as literal text. A good IDE will usually indicate this via syntax highlighting.
So, in your code, the Range() method is being passed the string A & Row_No instead of A5 -- so it errors out.