I’m trying to insert a GetPivotData formula into some cells.

There are up to 7 pivot tables to get the data, so I need to do it dynamically:

```
Function Formula(KPI As String, FilaTD As Integer, ColumnaTD As Integer, Filtro1 As String, _
Simple As Boolean, Optional Filtro2 As String)
If Simple = True Then
Formula = "IFERROR(GETPIVOTDATA(" & Comillas & KPI & Comillas & ",'TDReport Control Desk'!R" & _
FilaTD & "C" & ColumnaTD & "," & Filtro1 & ",RC2),0)"
Else
Formula = "IFERROR(GETPIVOTDATA(" & Comillas & KPI & Comillas & ",'TDReport Control Desk'!R" & _
FilaTD & "C" & ColumnaTD & "," & Filtro1 & ",RC2),GETPIVOTDATA(" & Comillas & KPI & Comillas & _
",'TDReport Control Desk'!R" & FilaTD & "C" & ColumnaTD & "," & Filtro2 & ",RC2))"
End If
End Function
```

The string called “Comillas” is just a constant:

```
Public Const Comillas As String = """"""
```

I call this function like this:

```
FormulaPrevisionAtenMesCentro = Formula(KPI2, FilaTDOffCentro, ColumnaTDOffCentro, "Centro", True)
FormulaPrevisionAtenDiaCentro = Formula(KPI2, _
FilaTDOffDiaCentro, ColumnaTDOffDiaCentro, "Centro", True)
FormulaPrevisionAtenMes = Formula(KPI2, _
FilaTDOffMes, ColumnaTDOffMes, "Modo2", False, "Modo3")
FormulaPrevisionAtenDia = Formula(KPI2, _
FilaTDOffDia, ColumnaTDOffDia, "Modo2", False, "Modo3")
FormulaKPIMes = Formula(KPI, _
FilaTDOffMes, ColumnaTDOffMes, "Modo2", False, "Modo3")
FormulaKPIMesCentro = Formula(KPI, FilaTDOffCentro, ColumnaTDOffCentro, "Centro", True)
FormulaKPIDia = Formula(KPI, _
FilaTDOffDia, ColumnaTDOffDia, "Modo2", False, "Modo3")
FormulaKPIDiaCentro = Formula(KPI, FilaTDOffDiaCentro, ColumnaTDOffDiaCentro, "Centro", True)
```

My problem is within the *Comillas* thing. If I use it, it will throw a VBA error. If I don’t use it, the formula will get inserted but won’t work, because the field I’m asking for, won’t be between ” “.

It should be:

```
Public Const Comillas As String = """"
```

since you only want the formula to contain a single quotation mark on each side of the value. You only need to double them up when putting a literal quoted string inside a formula string, not when concatenating it in.

Tags: excelexcel, function, vba