VBA间接数据验证

时间:2018-12-23 01:34:21

标签: excel vba excel-vba

我正在尝试通过VBA设置单元格的列表验证。当公式只是一个字符串时,我可以使用Formula1:=,但是当我尝试使用&组合变量时,这给了我400错误。带有级联变量的Formula1版本的问题似乎与以下事实有关:参考单元格具有#N / A值,但书面公式没有此问题。这是我最近的尝试:

Sub InsertRow()

    r = Worksheets("Kickoff Schedule").UsedRange.Rows.Count + Worksheets("Kickoff Schedule").UsedRange.Rows(1).Row - 1
    ...

    With Range("E" & r).Validation
        .Delete
        .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, _
            Formula1:="=INDIRECT($D" & CStr(r) & ")"
    End With

End Sub

我尝试过的所有事情的完整列表,如果它们没有/没有起作用:

' Works:
Formula1:="=INDIRECT($D19)"

' Works:
MsgBox "=INDIRECT($D" & CStr(r) & ")"
' MsgBox shows =INDIRECT($D19) , as expected

' Doesn't work:
Formula1:="=INDIRECT($D" & CStr(r) & ")"

' Doesn't work:
Formula1:="=INDIRECT(""" & Range("D" & r).Address(False, False) & """)"

' Shows one option with a string of the right formula, as expected:
Formula1:="INDIRECT($D" & CStr(r) & ")"

我在做什么错?预先感谢!

P.S。我已经读过Using Indirect function in Data Validation through VBA

1 个答案:

答案 0 :(得分:0)

您不需要在VBA中使用INDIRECT函数从文本创建公式或单元格引用。只需这样做:

reverse_dict = {value: key for key, value in dict.items()}