错误1004-使用变量而不是硬代码时,在OLAP多维数据集中找不到该项目

问题描述

我是VBA的新手,正在使用VBA自动执行任务。我需要从数据透视表中的一些数据复制到Excel文件中,该文件链接到外部数据源。我面临的困难是在枢轴字段中选择正确的时间段。

宏应以InputBox开头,以便用户输入日期,以便宏可以选择正确的月份以进行进一步处理。

YearMonth = InputBox("Input Year & Month of the report,e.g. 202007","Input Year & Month")
yr = Left(YearMonth,4)
mth = Right(YearMonth,2)

      If mth = "01" Then longmth = "JAN"
      If mth = "02" Then longmth = "FEB"
      If mth = "03" Then longmth = "MAR"
      If mth = "04" Then longmth = "APR"
      If mth = "05" Then longmth = "MAY"
      If mth = "06" Then longmth = "JUN"
      If mth = "07" Then longmth = "JUL"
      If mth = "08" Then longmth = "AUG"
      If mth = "09" Then longmth = "SEP"
      If mth = "10" Then longmth = "OCT"
      If mth = "11" Then longmth = "NOV"
      If mth = "12" Then longmth = "DEC"

PivotField的名称为“ Year”。该过滤器用于选择年份,该年份细分为季度,然后细分为月份(如下图所示)

PivotField picture

由于我不确定如何选择正确的月份,因此我尝试通过仅选择“ 2020 AUG”作为参考来记录宏。下面是记录的代码

    ActiveSheet.Pivottables("Pivottable1").PivotFields("[Time].[Time].[Year]"). _
        VisibleItemsList = Array("")
    ActiveSheet.Pivottables("Pivottable1").PivotFields("[Time].[Time].[Quarter]"). _
        VisibleItemsList = Array("")
    ActiveSheet.Pivottables("Pivottable1").PivotFields("[Time].[Time].[Month]"). _
        VisibleItemsList = Array("[Time].[Time].[Month].&[2020 AUG]")

因此,我想了解我可以创建一个变量(即下面的“ ExactDate”),以便选择标准基于用户在InputBox中的输入方式(例如202008->转换为“ 2020 AUG”),等等)

'Select the relevant month and year on the pivot table
    ExactDate = yr + " " + longmth
    
With ActiveSheet.Pivottables("Pivottable1")
    .PivotFields("[Time].[Time].[Year]").VisibleItemsList = Array("")
    .PivotFields("[Time].[Time].[Quarter]").VisibleItemsList = Array("")
    .PivotFields("[Time].[Time].[Month]").VisibleItemsList = Array("[Time].[Time].[Month].&[ExactDate]")

但是,它抛出“运行时错误'1004':在OLAP多维数据集中找不到该项目”。在Debug中,此代码突出显示

.PivotFields("[Time].[Time].[Month]").VisibleItemsList = Array("[Time].[Time].[Month].&[ExactDate]")

然后,我尝试用硬代码(即任何年份和月份,例如以下年份)替换变量“ ExactDate”:

.PivotFields("[Time].[Time].[Month]").VisibleItemsList = Array("[Time].[Time].[Month].&[2019 SEP]")

它有效。

我不知道为什么它不起作用,因为文本是完全一样的。唯一的区别是固定值与分配变量。

您能否建议如何使变量起作用?非常感谢!!!

解决方法

为了回答为什么需要双引号和&符的问题,这是我的完整答案:

在VBA中,您可以使用Dim语句声明变量(至少是推荐的方法)。

因此,在您的情况下,此行应作为良好做法出现:

Dim ExactDate as String

然后,文字字符串应该用双引号引起来。

在您的情况下,像这样:

"[Time].[Time].[Month].&["

要连接两个字符串或一个字符串和一个变量,可以使用与号&

因此,完成代码中的示例后,将用来过滤VisibleItemsList的字符串将是:

Array("[Time].[Time].[Month].&[" & ExactDate & "]"

由于ExactDate代表一个字符串,因此串联将起作用。

希望说明清楚。