为什么用于通过数据验证创建列表的Excel VBA代码不起作用?

时间:2017-11-21 08:43:26

标签: excel vba excel-vba

这是整个代码:

Dim Total_rows_Dash7 As Long
Dim Total_rows_Input7 As Long
Dim i7 As Long

Total_rows_Dash7 = Workbooks("Hourly Production Monitoring.xlsm").Worksheets("Dashboard").Range("B" & Rows.count).End(xlUp).Row
Total_rows_Input7 = Workbooks("Hourly Production Monitoring.xlsm").Worksheets("Input").Range("A" & Rows.count).End(xlUp).Row

For i7 = 2 To Total_rows_Input7
     With Worksheets("Input").Range("E" & i7).Validation
        .Delete
        .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
        xlBetween, Formula1:="='Dashboard'!$A$2:$A$25"
        .IgnoreBlank = True
        .InCellDropdown = True
        .InputTitle = ""
        .ErrorTitle = ""
        .InputMessage = ""
        .ErrorMessage = ""
        .ShowInput = True
        .ShowError = True
    End With
Next i7

错误的部分是这部分:

    .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
    xlBetween, Formula1:="='Dashboard'!$A$2:$A$25"

我也尝试过:

    .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
    xlBetween, Formula1:="='Dashboard'!$A$2:$A$" & Total_rows_Dash7 & ""

错误是:

enter image description here

我已经被困了一段时间,现在我不知道为什么它不起作用。

解决方案(Youtube视频): Solution

要使用数据验证引用另一个工作表,在某些情况下,您无法使用引用单元格或范围的常规方法(例如='WorksheetName'!A2:A25)(但大多数情况下您可以毫无问题)。如果您在引用标准方式时遇到问题,则必须选择要包含在列表中的项目,然后通过电子表格中的左上方框重命名该选项。然后,您必须通过在数据验证的源框中键入选择的名称来引用它: = NameOfSelection (注意没有任何排序的标点符号,也没有单元格/范围引用)

然后动态更新它。您可以使用宏来确定如何根据您自己的条件动态命名项目列表。

工作代码:

Dim Total_rows_Dash7 As Long
Dim Total_rows_Input7 As Long
Dim i7 As Long

Total_rows_Dash7 = Workbooks("Hourly Production Monitoring.xlsm").Worksheets("Dashboard").Range("B" & Rows.count).End(xlUp).Row
Total_rows_Input7 = Workbooks("Hourly Production Monitoring.xlsm").Worksheets("Input").Range("A" & Rows.count).End(xlUp).Row

ActiveWorkbook.Names.Add Name:="JobTicketNo", RefersToR1C1:= _
        "=Dashboard!R2C1:R" & Total_rows_Dash7 & "C1"

For i7 = 2 To Total_rows_Input7
     With Workbooks("Hourly Production Monitoring.xlsm").Worksheets("Input").Range("E" & i7).Validation
        .Delete
        .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
        xlBetween, Formula1:="=JobTicketNo"
        .IgnoreBlank = True
        .InCellDropdown = True
        .InputTitle = ""
        .ErrorTitle = ""
        .InputMessage = ""
        .ErrorMessage = ""
        .ShowInput = True
        .ShowError = True
    End With
Next i7

以下是使用常规引用方式时的错误: Error

1 个答案:

答案 0 :(得分:0)

这一行

With Worksheets("Input").Range("E" & i7).Validation

可能正在努力使用正确的工作簿。

通过..

确认该名称
With Workbooks("xxx").Worksheets("Input").Range("E" & i7).Validation