Excel VBA Pivot Table Calculated Field Creation Using Variables - excel

I have looked around SO and haven't found an answer to this type of question. It is probably something trivial that I am doing wrong, but I have tried several different formats of the below with no success. I have a very long VBA script which uses calculations to determine which fields to include in the pivot. I then take the variable fields returned and turn them into variables (pivot1, pivot2, etc.). I can't name the fields specifically in the addition of the calculated field, as I don't know what they will be. The second segment of code throws off the error "Unable to get the PivotFields property of the PivotTable class". Any help with this would be much appreciated.
ActiveSheet.PivotTables("Pivot Table 1").CalculatedFields.Add "Total", "= pivot1 _
& " + " & pivot2 & " + " & pivot3 & " + " & pivot4 & " + " & pivot5 & " + " & pivot6 _
& " + " & pivot7 & " + " & pivot8 & " + " & pivot9 & " + " & pivot10 & " + " & pivot11 _
& " + "& pivot12", True
ActiveSheet.PivotTables("Pivot Table 1").AddDataField ActiveSheet.PivotTables _
("Pivot Table 1").PivotFields("Total"), "Grand Total", xlSum

Related

Excel VBA .Formula - syntax error adding absolute reference to cell

I have a syntax error in this VBA code:
students.Cells(studentRow, StartColumn).Formula = _
"=If($" & SurnameColumnStr & studentRow & " <> """", if($" & colonnaStr & studentRow & _
" <> """", $" & colonnaStr & " & $" & pointRow & ", 0), """")"
I can't put right this piece of code: $" & colonnaStr & " & $" & pointRow & " (it would be like having "$B$3")
I've tried several ways with no luck.
Any help would be really appreciated.
To get "$B$3" out of colonnaStr (a column reference) and pointRow (a row reference), you will need to use Range.Address.
Using this inside your Formula String:
Range(colonnaStr & pointRow).Address(True, True, xlA1)
Will give you $B$3 as a result.
To learn more about is, read HERE

Select rows based on the values in a column

I have an Excel file with a userform where users can insert exchange rates and different parameters for financial report.
I set up a DB file and I want to select rows based on the values in BV column (book value) and it should be higher than 100.000EUR.
The problem is that I have three other currencies besides EUR and I need to calculate EUR amount based on exchange rate.
I made an exchange rate field in my userform (BVAL is EUR default, and I also have BVGBP, BVPLN and BVRSD, which are 100.000EUR divided by each exchange rate).
This works:
SqlQuery = " SELECT * FROM Sheet1 where (bv>=" & BVAL & " and Currency = 'EUR')";"
But when I try to combine multiple results, syntax is not working. I tried other solutions found online.
SqlQuery = " SELECT * FROM Sheet1 where (bv>=" & BVAL & " and Currency='EUR') or (bv>=" & BVGBP & " and Currency='GBP') _
or (bv>=" & BVPLN & " and Currency='PLN') or (bv>=" & BVRSD & " and Currency='RSD');"
You SQL syntax is correct, but your VBA is not. Also, for better readability, break up the long lines:
SqlQuery = " SELECT * FROM Sheet1 where " & _
"(bv>=" & BVAL & " and Currency='EUR') or " & _
"(bv>=" & BVGBP & " and Currency='GBP') or " & _
"(bv>=" & BVPLN & " and Currency='PLN') or " & _
"(bv>=" & BVRSD & " and Currency='RSD');"

Querying data between a specific date and time in VBA

I have a database in access where every data has a date and time in two different columns.
I need to to run a query in excel using VBA which would fetch me data between two specific dates and times (eg: 01/05/2016 13:15 and 03/05/2016 10:11)
My query is as follows:
SQL = "SELECT * FROM " & database & " WHERE symbol='" & companyName & _
"' AND AdmitDate BETWEEN " & (fromDate + fromTime) & " AND " & (toDate + toTime) & ""
However, it gives me a syntax error which says:
'Missing operator in query expression'
I am not able to figure out where I have gone wrong.
Please help!
You need the right string expressions for the date/time values. Format can create these:
SQL = "SELECT * FROM " & database & " WHERE symbol='" & companyName & "' AND AdmitDate BETWEEN #" & Format(fromDate + fromTime, "yyyy\/mm\/dd hh\:nn\:ss") & "# AND #" & Format(toDate + toTime, "yyyy\/mm\/dd hh\:nn\:ss") & "#"

Weighted average rate in VBA

I am quite new to VBA so I am sorry if my question might seems very trivial.
I would love to write a function in VBA which helps to estimate weighted average rate (for loan portfolio, for instance). I wrote the following VBA code:
Function WAIRS(Amount As Range, InterestRate As Range, MatchRange As Range, Match1)
WAIRS = Evaluate("=SUMPRODUCT(--(""" & MatchRange & """ = """ & Match1 & """),""" & Amount & """, """ & InterestRate & """)") /Application.WorksheetFunction.SumIfs(Amount, MatchRange, Match1)
End Function
The problem is that when I run this function in Excel by adding respective function criterias I get an "#VALUE#". I have tried a lot but cannot find out what is wrong. I Would highly appreciate if you can help me.
Thank you in advance.
Best,
Jeyhun
The string you build for Evaluate should (in this case) not include literal double quotes. Instead of quoting the result of a range value
"""" & MatchRange & """"
...you should retrieve the address notation of that range, and use that without wrapping it in quotes:
MatchRange.Address()
If you apply that consistently, it would make the Evaluate part of the formula look like this:
"=SUMPRODUCT(--(" & MatchRange.Address() & " = " & Match1.Address() & "), " & _
Amount.Address() & ", " & InterestRate.Address() & ")"
When range is another sheet:
The above will not work if your ranges are on another sheet. In that case, I would suggest to create this function:
Public Function fullAddr(range As Range)
fullAddr = "'" & range.Parent.Name & "'!" & _
range.Address(External:=False)
End Function
And then in your formula:
"=SUMPRODUCT(--(" & fullAddr(MatchRange) & " = " & fullAddr(Match1) & "), " & _
fullAddr(Amount) & ", " & fullAddr(InterestRate) & ")"

how to add a test for non-black cells using `FormulaR1C1' in excel vba

I'm trying to insert the following equation into a sheet:
=COUNTIFS(email_logs_output.csv!$AB$2:$AB$26731, _
usersFullOutput.csv!S26, _
email_logs_output.csv!$R$2:$R$26731, _
"<>"&"", _
email_logs_output.csv!$H$2:$H$26731, _
"gift*")
I'm getting stuck at the criteria "<>"&"". Here's what I have:
With Worksheets(users_sheet)
equation_range.FormulaR1C1 = "=COUNTIFS(" & emails_sheet & "!R2C" & email_col & ":R" & rows_email & "C" & email_col & " , RC[" & col_back & "], " _
& emails_sheet & "!R2C18:R" & rows_email & "C18, "" " <> " & "" "")"
End With
When I run it, all I get is TRUE in every cell in equation_range.
How do I get the equation to include "<>"&""?
Just tried one formula and this works
[a1].FormulaR1C1 = "=countif(R1C3,""<>"" & ""a"")"
So in your case
...C18,""<>"" & "" "")"
Notes
Basicaly, whenever you have "text" in your formula just put ""text"" and that should do the trick.
Another thing : Beware of the "autospreading" of the code in VBA environment. Check for non wanted spaces added automaticaly where you may not want them.

Resources