Replacing code in text with variables

Rowanhf12

New Member
Joined
Jan 22, 2016
Messages
27
Hi

I have the following code

Code:
    Dim Ch1 As Excel.Range
    Set Ch1 = Range("J11")

    ActiveSheet.PivotTables("PivotTable1").PivotFields("Average of Cost").Function = " & Ch1 & "

The variable in cell J11 will be Average, but the section of the code " & Ch1 & " should read xlAverage.
I'm getting the run-time error 1004 at the moment.
I want this to be a variable
(I know that if they change the Average to Sum etc, then the piece of code that says Average of Cost should read Sum of Cost etc)

Any help???
 

Excel Facts

Excel motto
Not everything I do at work revolves around Excel. Only the fun parts.
You can't do what you want. It's as if you wanted to change
If X=5 Then...
to
Strg1="If "
Strg1 X=5 Then...

It just doesn't work that way. You can do something like this
If Ch1="xlAverage" then ActiveSheet.PivotTables("PivotTable1").PivotFields("Average of Cost").Function = xlAverage
and may be nested ifs or Case statements to handle the others like xlSum, etc.
 
Upvote 0
Ahh, well that's annoying. But thank you for clearing that up.

Just in case anyone has the same problem in the future and stumbles upon this thread.
Below is the code I used:

Code:
    If InStr(1, ActiveSheet.Range("I11").Value, "Average") > 0 Then
    ActiveSheet.PivotTables("PivotTable1").PivotFields("Average of Cost").Function = xlAverage
    End If

and then repeat the 'If' statements for the other possible outcomes in Pivot - sum, count etc
 
Upvote 0

Forum statistics

Threads
1,215,046
Messages
6,122,854
Members
449,096
Latest member
Erald

We've detected that you are using an adblocker.

We have a great community of people providing Excel help here, but the hosting costs are enormous. You can help keep this site running by allowing ads on MrExcel.com.
Allow Ads at MrExcel

Which adblocker are you using?

Disable AdBlock

Follow these easy steps to disable AdBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the icon in the browser’s toolbar.
2)Click on the "Pause on this site" option.
Go back

Disable AdBlock Plus

Follow these easy steps to disable AdBlock Plus

1)Click on the icon in the browser’s toolbar.
2)Click on the toggle to disable it for "mrexcel.com".
Go back

Disable uBlock Origin

Follow these easy steps to disable uBlock Origin

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back

Disable uBlock

Follow these easy steps to disable uBlock

1)Click on the icon in the browser’s toolbar.
2)Click on the "Power" button.
3)Click on the "Refresh" button.
Go back
Back
Top