EXCEL VBA问题返回#VALUE!通过数据透视表

时间:2017-05-10 14:45:52

标签: vba excel-vba pivot-table excel

我是VBA编程的新手,我遇到了一个奇怪的问题。 所以我有一个包含3种行的数据透视表("用户","全名","权限")。

我编写了一个程序,在x中查找某个名称PivotTable,一旦找到了名称,就会查看以下内容"权限"并返回" True"如果他们有权限'。现在回到" True"工作正常,但由于某种原因每次失败而不是像我认为的那样返回错误它会返回#VALUE!,有人知道为什么吗?

Public Function Dependency(x As String) As String

Dim rngRow As Range
Dim pt As PivotTable
Dim pf2Value As String
Dim pf3Value As String

pf2Value = "False"
pf3Value = "False"
Set pt = ActiveSheet.PivotTables("PivotTable1")

For Each rngRow In pt.RowRange        
    If pf2Value = "True" And rngRow.PivotField.Name = "Permissions" Then
        If rngRow.Value = "Has Permissions" Then
                pf3Value = "True"
        End If
    End If
    If pf2Value = "True" And pf3Value = "True" And rngRow.PivotField.Name <> "Permissions" Then Exit For
    If rngRow.PivotField.Name = "Full Name" And rngRow.Value = x Then
        pf2Value = "True"
    End If
    If rngRow.PivotField.Name = "Full Name" And rngRow.Value <> x Then
        pf2Value = "False"
    End If
Next rngRow
Dependency = pf3Value

End Function

如果我这样做,它会返回false:

Public Function Dependency(x As String) As String

Dim rngRow As Range
Dim pt As PivotTable
Dim pf2Value As String
Dim pf3Value As String

pf2Value = "False"
pf3Value = "False"
Set pt = ActiveSheet.PivotTables("PivotTable1")

For Each rngRow In pt.RowRange
Next rngRow
Dependency = pf3Value

End Function

当我添加这一行时,问题就出现了:

Public Function Dependency(x As String) As String

Dim rngRow As Range
Dim pt As PivotTable
Dim pf2Value As String
Dim pf3Value As String

pf2Value = "False"
pf3Value = "False"
Set pt = ActiveSheet.PivotTables("PivotTable1")

For Each rngRow In pt.RowRange
    If pf2Value = "True" And rngRow.PivotField.Name = "Permissions" Then
    End If
Next rngRow
Dependency = pf3Value

End Function

1 个答案:

答案 0 :(得分:0)

尝试下面的代码(代码中的注释作为注释):

公共功能依赖代码

Sub TestDependency()

MsgBox Dependency("John Doe")

End Sub

Sub TestDependency 代码(测试功能)

{{1}}