How to use variables to set pivot table Function parameters with VBA? - vba

I would like to use variables to specifying parameters of pivot table. Most of them are working correctly, but 2 of them not. The “function” parameters “xli” and “ValueFilterQuant(pos)” don’t come up with any values. I tried it write between quotation marks and quotation marks-& but nothing happened. Is there any method to set Function parameters with variables? This is the snippet of code:
For pos = 1 To UBound(ValueQuant)
If ValueQuant(pos) = "Work" Then
xli = "xlSum"
Label = "Sum of "
Else
xli = "xlCount"
Label = "Count of "
End If
ActiveSheet.PivotTables("PivotTable1").CubeFields.GetMeasure "[database].[" & ValueQuant(pos) & "]" _
, xli, "" & Label & "" & ValueQuant(pos) & ""
ActiveSheet.PivotTables("PivotTable1").AddDataField ActiveSheet.PivotTables( _
" PivotTable1").CubeFields("[Measures].[" & Label & "" & ValueQuant(pos) & "]"), "" & Label & "" & ValueQuant(pos) & ""
With ActiveSheet.PivotTables("PivotTable1").PivotFields( _
"[Measures].[" & Label & "" & ValueQuant(pos) & "]")
.Caption = "" & ValueFilterQuantaf(pos) & "" & ValueQuant(pos) & ""
.Function = ValueFilterQuant(pos)
End With
Next

The code is incomplete. I don't know where ValueFilterQuant(pos) is coming from.
I suspect that like xli = "xlSum" it is returning a string variable, but the thing is that those parameters should not be strings. They are numbers that are derived from an XlConsolidationFunction enumeration.
So something like:
If ValueQuant(pos) = "Work" Then
xli = XlConsolidationFunction.xlSum '-4157
Label = "Sum of "
Else
xli = XlConsolidationFunction.xlCount '-4112
Label = "Count of "
End If
Same thing needs to happen for ValueFilterQuant(pos).
Note that it is more work to derive a dynamic enumeration at runtime through a string. I guess that you are reading a string value in off a worksheet or similar process.
You could set them up in a dictionary beforehand, and pick out the numbers that way.
The list of values is here: https://msdn.microsoft.com/en-us/library/office/ff837374.aspx

Related

Recordset Not Updating Table with Changed and/or Correct Values

The codes purpose is to 'build' the correct name style for each record in a CDSal and FormatName field. I have a group of tables (all linked) with individuals Full Name(NewName), Salutation, First, Middle and Last Name, as well as Client defaults for what to do with those names (!NewName, !First, !AA, etc.).
The Recordset is pulled from a query in the database that brings some necessary fields together from 2 different tables. From Access I can open the query, make any changes needed to any of the fields, save the record and see the changes reflected in the underlying tables. When I run the following code, the Debug.Print's produce the expected outcomes but nothing is permanently saved to the tables. The code never errors (which might be part of the problem) and for Case "!AA" both CDSal and FormatName fields are filled with !NewName when Debug.Print again shows the expected outcome. Case "!AA" is the only instance where anything is actually changed on the tables.
I have attempted everything that I could find on the Internet to troubleshoot this error as well as multiple different configurations to get something to "stick". Hopefully it is a simple answer, let me know what you all think.
Private Sub Form_Load()
On Error GoTo Form_Load_Err
'_ SetUp Variables _'
Dim strQry As String, strSQL As String, strName As String
Dim rstName As DAO.Recordset
'_ Declare Variables _'
strQry = "MyQueryName"
Set rstName = CurrentDb.OpenRecordset(strQry, dbOpenDynaset)
'_ Begin Code _'
With rstName
If Not (.EOF And .BOF) Then .MoveFirst
Do Until .EOF = True
'Update CDSal with correct Naming Information
Debug.Print !NewName
.Edit
Select Case !CDSal_Client
Case "NewName" 'Clients that use NewName for blah
!CDSal = !NewName
Case "First" 'Clients that use First for blah
!CDSal = !First
Case "AA" 'ClientName: CDSal = First, FormatName = NewName(w/o Sal)
!CDSal = !First
If !Sal <> "" Then
!FormatName = !First & " " & !Middle & " " & !Last
Else
!FormatName = !NewName
End If
Case "BB" 'ClientName: Client uses specific breakdown for names
If !Sal <> "" And !Last <> "" Then
!CDSal = !Sal & " " & !Last
!FormatName = !Sal & " " & !Last
ElseIf !First <> "" And !Last <> "" Then
!CDSal = !First & " " & !Last
!FormatName = !First & " " & !Last
ElseIf !First <> "" Then
!CDSal = !First
!FormatName = !First
Else
!CDSal = "Valued Member"
!FormatName = "Valued Member"
End If
Case "CC" 'ClientName: CDSal = NewName(trim " & " if needed) = NewName + AddlName(done on import)
If Right(!NewName, 3) = " & " Then
Replace !NewName, " & ", ""
!CDSal = !NewName
Else
!CDSal = !NewName
End If
End Select
.Update
Debug.Print !CDSal
Debug.Print !FormatName
.MoveNext
Loop
'Removes additional spaces left over from concatenating fields
strSQL = "UPDATE [" & strQry & "] SET [FormatName] = REPLACE(REPLACE(REPLACE([FormatName],' ','<>'),'><',''),'<>',' '), " & _
"[CDSal] = REPLACE(REPLACE(REPLACE([FormatName],' ','<>'),'><',''),'<>',' ');"
CurrentDb.Execute strSQL
End With
'_ Error Handling & CleanUp
Form_Load_ClnUp:
rstName.Close
Set rstName = Nothing
Exit Sub
Form_Load_Err:
MsgBox Err.SOURCE & " : " & Err.Number & vbCr & _
"Error Description : " & Err.Description
GoTo Form_Load_ClnUp
End Sub
MyQueryName SQL
SELECT T_Individual.ID_IndivRecords, T_Individual.NewName, T_Individual.NewName2, T_Individual.CDSal, T_Individual.FormatName, T_Individual.Status_, T_Individual.Sal, T_Individual.First, T_Individual.Middle, T_Individual.Last, T_Clients.ID_Client, T_Clients.CDSal_Client, T_Individual.Date
FROM T_Individual INNER JOIN (T_Clients INNER JOIN (T_Jobs INNER JOIN T_IndivJobs ON T_Jobs.ID_Jobs = T_Individual.Jobs) ON T_Clients.ID_Client = T_Jobs.Client) ON T_Individual.ID_IndivRecords = T_IndivJobs.ID_DonorRecords
WHERE (((T_Individual.Date)=Date()));
strSQL = "UPDATE [" & strQry & "] SET [FormatName] = REPLACE(REPLACE(REPLACE([FormatName],' ','<>'),'><',''),'<>',' '), " & _
"[CDSal] = REPLACE(REPLACE(REPLACE([FormatName],' ','<>'),'><',''),'<>',' ');"
Another instance of a simple error and or mistype can drastically affect everything you are trying to achieve. This SQL was ran after the code was processed to remove any double spaces that might have been in the original data or created from concatenation. Notice that the CDSal field will be replaced with the FormatName field in the last line instead of being replaced with itself. Since most records do not use the FormatName field their CDSal field was getting replaced with NULL . . .
I have corrected this issue and everything runs very smoothly and correctly now.
Thanks for everyone who tried to help on this! Any additional information on Formatting or Optimization is always appreciated.

Can't get the tabs value (name) in VBA macro

I'm stuck here. below is my vba macro. I want to lookup againts other tabs but the result only give me
=VLOOKUP(BE2, $BQ$2:$BQ$6, 1, 0) but not the tabs name.. Why? How can I get the sheets name?
Set myValues = Application.InputBox("Please select a:", Type:=8)
Set myResults = Application.InputBox("Please select a next sheet:", Type:=8)
On Error Resume Next
Set myValues = myValues.Offset
FirstRow = myValues.Row
FinalRow = Cells(65536, myResults.Column).End(xlUp).Row
Range("BF2").Formula = _
"=VLOOKUP(" & Cells(FirstRow, myValues.Column).Address(False, False) & ", " & _
" " & myResults.Address & " , 1, 0)"
You're close. You just need to set the Address External argument to True.
Something like:
myResults.Address(External:=True)
The .Address property only returns the row and column reference unless you set the External parameter to True. See below:
Range("BF2").Formula = _
"=VLOOKUP(" & Cells(FirstRow, myValues.Column).Address(False, False) & ", " & _
" " & myResults.Address(External:=True) & " , 1, 0)"
If you don't want the workbook name in the reference, you can build the reference using the .Worksheet.Name property of the Range object. See below:
Range("BF2").Formula = _
"=VLOOKUP(" & Cells(FirstRow, myValues.Column).Address(False, False) & ", " & _
" " & myResults.Worksheet.Name & "!" & myResults.Address & " , 1, 0)"
See the Range.Address Property on MSDN for more information.

How to use many checkbox values in a Query

My goal is to return the results of 5 textboxes into a SQL query, by incorporating the Query string with the variables.
How can I get my code to function so that when a checkbox is checked, the value (eg: ID, SC...) is recorded and placed into a Query? And if a checkbox is not checked, then it is not placed into the query.
The 5 checkboxes are as follows:
The code I current have to record whether a textbox is selected, and to place the value (eg: ID, SC, AS...) into a variable is as follows:
If (Me.BoxID = False) And (Me.BoxSC = False) And (Me.BoxASSC = False) And (Me.BoxAS = False) And (Me.BoxEH = False) Then
MsgBox "You must check a Fonction Checkbox", 0
Exit Sub
Else
If (Me.BoxID= True) Then IDValue = Chr(34) & "ID" & Chr(34) Else IDValue = """"""
If (Me.BoxSC= True) Then SCValue = Chr(34) & "SC" & Chr(34) Else SCValue = """"""
If (Me.BoxASSC= True) Then ASSCValue = Chr(34) & "ASSC" & Chr(34) Else ASSCValue = """"""
If (Me.BoxAS= True) Then ASValue = Chr(34) & "AS" & Chr(34) Else ASValue = """"""
If (Me.BoxEH= True) Then EHValue = Chr(34) & "EH" & Chr(34) Else EHValue = """"""
End If
fonctionQryString = "(((tblF.f1)=" & IDValue & ") OR " + "((tblF.f1)=" & SCValue & ") OR " + "((tblF.f1)=" & ASSCValue & ") OR " + "(tblF.f1)=" & ASValue & ") OR " + "(tblF.f1)=" & EHValue & ")))"
The fonctionQryString goes into the WHERE section of the SQL Query.
I know that the method I'm using is not efficient, even though it works.
My problem is that I don't know how to do this another way. I want my code to function so that when a checkbox is not checked, it doesn't go into the Query string.
Any help would be much appreciated.
These two WHERE clauses should produce equivalent results. Consider switching to the second form.
WHERE tblF.f1 = "ID" OR tblF.f1 = "SC" OR tblF.f1 = "AS"
WHERE tblF.f1 IN ("ID","SC","AS")
Here is a rough and untested code sample to produce a similar WHERE clause based on my understanding of what you're trying to achieve.
Dim fonctionQryString As String
Dim lngLoopNum As Long
Dim strControlName As String
Dim strValueList As String
For lngLoopNum = 1 To 5
Select Case lngLoopNum
Case 1
strControlName = "ID"
Case 2
strControlName = "SC"
Case 3
strControlName = "ASSC"
Case 4
strControlName = "AS"
Case 5
strControlName = "EH"
End Select
If Me.Controls("Box" & strControlName) = True Then
strValueList = strValueList & "," & Chr(34) & _
strControlName & Chr(34)
End If
Next
If Len(strValueList) > 0 Then
fonctionQryString = "tblF.f1 IN (" & Mid(strValueList, 2) & ")"
Else
MsgBox "You must check a Fonction Checkbox"
End If
I assumed you didn't actually want to include the condition, WHERE tblF.f1 = "" (an empty string). If I guessed wrong, you'll have more work to do, but hopefully this will still point you to something useful.

Ms-Access how to use a query with a parameter inside a form

I have an SQL query with a question(alert like) that pops up every time I open it...
For every value inserted in that question you get diffrent result.
I Want to be able to use that query in my form with a combo-box...
I don't know how to exceute the query with the parameter from within the form....
I have no problem using VBA, just tell me how to call the query with the parameter
Thanks,
Fingerman
I usually use my filtering forms using the following principles:
1) I first create a query that includes all the fields I want to display and all the fields I want to filter on. It can use more than one table. I do not set any criteria (WHERE clause) in this query unless there is a condition that always needs to be applied no matter what.
2) Next I create a datasheet form based on this query and I save it, giving it a name that indicates that it's a subform.
3) Next I create an unbound main form and add unbound controls such as textboxes, combos, listboxes, checkboxes, etc. that will be used to filter the different fields. One control can potentially allow a user to search on more than one field depending how you write your filtering routine in VBA.
4) Now it's time to write code on the main form to make this all work. Basically, the code needs to check to see if there are values in any of the controls and if so, it creates a WHERE clause (without the WHERE keyword) and at the very end it sets the subform's filter property and turns the subform's FilterOn property to TRUE.
Here's some example code. This was taken from the sample database I've made just to demonstrate filtering (see below). This example does not use fuzzy searches (asterisks) and each control on the main form only filters one field on the subform.
Private Sub cmdFilter_Click()
'You can also call the FilterSubForm function on a control's AfterUpdate event.
Call FilterSubform
End Sub
Private Sub FilterSubform()
Dim strFilter As String
'Note: We have to wrap field names in brackets if they contain spaces or
'special characters. These fields are in Northwind Traders 2007 from Microsoft
'I would never consider naming my fields with spaces or special characters
'in them.
'Company
If Nz(Me.txtCompany, "") <> "" Then
strFilter = strFilter & "Company = '" & PQ(Me.txtCompany) & "' And "
End If
'First Name
If Nz(Me.txtFirstName, "") <> "" Then
strFilter = strFilter & "[First Name] = '" & PQ(Me.txtFirstName) & "' AND "
End If
'Last Name
If Nz(Me.txtLastName, "") <> "" Then
strFilter = strFilter & "[Last Name] = '" & PQ(Me.txtLastName) & "' AND "
End If
'Business Phone
If Nz(Me.txtBusinessPhone, "") <> "" Then
strFilter = strFilter & "[Business Phone] = '" & PQ(Me.txtBusinessPhone) & "' AND "
End If
'City
If Nz(Me.cboCity, "") <> "" Then
strFilter = strFilter & "City = '" & PQ(Me.cboCity) & "' AND "
End If
'State/Province
If Nz(Me.cboStateProvince, "") <> "" Then
strFilter = strFilter & "[State/Province] = '" & PQ(Me.cboStateProvince) & "' AND "
End If
'Order Date
If Nz(Me.txtOrderDate, "") <> "" Then
If IsDate(Me.txtOrderDate) = True Then
strFilter = strFilter & "[Order Date] = #" & Me.txtOrderDate & "# AND "
End If
End If
'Ship Name
If Nz(Me.txtShipName, "") <> "" Then
strFilter = strFilter & "[Ship Name] = '" & PQ(Me.txtShipName) & "' AND "
End If
'Ship City
If Nz(Me.txtShipCity, "") <> "" Then
strFilter = strFilter & "[Ship City] = '" & PQ(Me.txtShipCity) & "' AND "
End If
'Ship State/Province
If Nz(Me.cboShipStateProvince, "") <> "" Then
strFilter = strFilter & "[Ship State/Province] = '" & PQ(Me.cboShipStateProvince) & "' AND "
End If
'Product Code
If Nz(Me.cboProductCode, "") <> "" Then
strFilter = strFilter & "[Product Code] = '" & PQ(Me.cboProductCode) & "' AND "
End If
'Quantity
If Nz(Me.txtQuantity, "") <> "" Then
If IsNumeric(Me.txtQuantity) = True Then
strFilter = strFilter & "Quantity = " & Me.txtQuantity & " AND "
End If
End If
If Right(strFilter, 5) = " AND " Then strFilter = Left(strFilter, Len(strFilter) - 5)
If strFilter <> "" Then
Me.subformOrderSearch.Form.Filter = strFilter
Me.subformOrderSearch.Form.FilterOn = True
Else
'Clear the filter
Me.subformOrderSearch.Form.Filter = ""
Me.subformOrderSearch.Form.FilterOn = False
End If
End Sub
Private Function PQ(s As String) As String
'This function is used to "pad quotes" for SQL
PQ = Replace(s, "'", "''")
End Function
I've put together a sample database that has several different examples all building on what I've posted here. You can download this database here:
http://www.utteraccess.com/forum/Search-filtering-Examples-t1968063.html
After some Searching, I have came across this:
http://www.techrepublic.com/blog/msoffice/run-a-parameter-query-within-an-access-form/701
It is not what I wanted, But it is a great solution...
I will wait, if no one gets a better answer, I'll accept my own (As much as I hate doing that).

VB.NET - using textfile as source for menus and textboxes

this is probably a bit tense and I'm not sure if this is possible at all.
But basically, I'm trying to create a small application which contains alot of PowerShell-code which I want to run in an easy matter.
I've managed to create everything myself and it does work. But all of the PowerShell code is manually hardcoded and this gives me a huge disadvantage.
What I was thinking was creating some sort of dynamic structure where I can read a couple of text files (possible a numerous amount of text files) and use these as the source for both the comboboxes and the richtextbox which provovides as the string used to run in PowerShell.
I was thinking something like this:
Combobox - "Choose cmdlet" - Use "menucode.txt" as source
Richtextbox - Use "code.txt" as source
But, the thing is, Powershell snippets need a few arguments in order for them to work.
So I've got a couple of comboboxes and a few textboxes which provides as input for these arguments. And this is done manually as it is right now. So rewriting this small application should also search the textfile for some keywords and have the comboboxes and textboxes to replace those keywords. And I'm not sure how to do this.
So, would this requre a whole lot of textfiles? Or could I use one textfile and separate each PowerShell cmdlet snippets with something? Like some sort of a header?
Right now, I've got this code at the eventhandler (ComboBox_SelectedIndexChanged)
If ComboBoxFunksjon.Text = "Set attribute" Then
TxtBoxUsername.Visible = True
End If
If chkBoxTextfile.Checked = True Then
If txtboxBrowse.Text = "" Then
MsgBox("You haven't choses a textfile as input for usernames")
End If
LabelAttribute.Visible = True
LabelUsername.Visible = False
ComboBoxAttribute.Visible = True
TxtBoxUsername.Visible = False
txtBoxCode.Text = "$users = Get-Content " & txtboxBrowse.Text & vbCrLf & "foreach ($a in $users)" & vbCrLf & "{" & vbCrLf & "Set-QADUser -Identity $a -ObjectAttributes #{" & ComboBoxAttribute.SelectedItem & "='" & TxtBoxValue.Text & "'}" & vbCrLf & "}"
If ComboBoxAttribute.SelectedItem = "Outlook WebAccess" Then
TxtBoxValue.Visible = False
CheckBoxValue.Visible = True
CheckBoxValue.Text = "OWA Enabled?"
txtBoxCode.Text = "$users = Get-Content " & txtboxBrowse.Text & vbCrLf & "foreach ($a in $users)" & vbCrLf & "{" & vbCrLf & "Set-CASMailbox -Identity $a -OWAEnabled" & " " & "$" & CheckBoxValue.Checked & " '}" & vbCrLf & "}"
End If
If ComboBoxAttribute.SelectedItem = "MobileSync" Then
TxtBoxValue.Visible = False
CheckBoxValue.Visible = True
CheckBoxValue.Text = "MobileSync Enabled?"
Dim value
If CheckBoxValue.Checked = True Then
value = "0"
Else
value = "7"
End If
txtBoxCode.Text = "$users = Get-Content " & txtboxBrowse.Text & vbCrLf & "foreach ($a in $users)" & vbCrLf & "{" & vbCrLf & "Set-QADUser -Identity $a -ObjectAttributes #{msExchOmaAdminWirelessEnable='" & value & " '}" & vbCrLf & "}"
End If
Else
LabelAttribute.Visible = True
LabelUsername.Visible = True
ComboBoxAttribute.Visible = True
txtBoxCode.Text = "Set-QADUser -Identity " & TxtBoxUsername.Text & " -ObjectAttributes #{" & ComboBoxAttribute.SelectedItem & "='" & TxtBoxValue.Text & " '}"
If ComboBoxAttribute.SelectedItem = "Outlook WebAccess" Then
TxtBoxValue.Visible = False
CheckBoxValue.Visible = True
CheckBoxValue.Text = "OWA Enabled?"
txtBoxCode.Text = "Set-CASMailbox " & TxtBoxUsername.Text & " -OWAEnabled " & "$" & CheckBoxValue.Checked
End If
If ComboBoxAttribute.SelectedItem = "MobileSync" Then
TxtBoxValue.Visible = False
CheckBoxValue.Visible = True
CheckBoxValue.Text = "MobileSync Enabled?"
Dim value
If CheckBoxValue.Checked = True Then
value = "0"
Else
value = "7"
End If
txtBoxCode.Text = "Set-QADUser " & TxtBoxUsername.Text & " -ObjectAttributes #{msExchOmaAdminWirelessEnable='" & value & "'}"
End If
End If
Now, this snippet above lets me either use a text file as a source for each username used in the powershell snippet. Just so you know :) And I know, this is probably coded as stupidly as it gets. But it does work! :)
It'll probably get fairly horrible to debug when you've been away from it for a year and are trying to figure out how it hangs together, but if you're doing it I'd suggest that this might be a good time to use XML, since you can then create a nice structure to the files easily that will be fairly easy to understand.
<commands>
<command>
<name>Cmd1</name>
<buttonText>NiceName</buttonText>
<parameters>
<parameter>textBox1</parameter>
<parameter>textBox2</parameter>
<parameter>comboBox1</parameter>
</parameters>
<code>your code here</code>
</command>
<command>
...
</command>
</commands>
You'd have to be careful if your script code contains any characters that can interfere with the xml though.