简体   繁体   English

使用VBA代码将Excel中的数据验证(下拉列表)分为整列

[英]Data Validation (Drop-Down List) in Excel into a whole column using VBA code

I have managed to insert data validation (drop down list) into a single row in the column. 我设法将数据验证(下拉列表)插入到该列的单行中。 However, I want to expand the data validation until the last row. 但是,我想将数据验证扩展到最后一行。

I can't find anywhere about data validation being expanded until the last row. 在最后一行之前,我找不到关于扩展数据验证的任何信息。 just to clarify, it's not about changing the list of data validation, it's to have data validation in each row until the last row. 只是为了澄清,不是要更改数据验证的列表,而是要在每行直到最后一行都有数据验证。

Sub datavalidation()

Dim ws As Worksheet
Dim tbl As ListObject
Dim neC As Range


Set ws = ActiveSheet
Set tbl = ws.ListObjects("Table1")
Set neC = tbl.DataBodyRange(1, 3)

With neC.Validation
.Delete
.Add Type:=xlValidateList, _
    AlertStyle:=xlValidAlertStop, _
    Operator:=xlBetween, _
    Formula1:="=Table2"

.ErrorMessage = "Month"
.ErrorMessage = "Please select January until December from the list"

End With

End Sub

The code runs smoothly. 代码运行平稳。 however, where do i add/change if i want data validation to apply to the next row till the last? 但是,如果我想将数据验证应用于下一行直到最后一行,该在哪里添加/更改?

You can apply validation lists to an entire range. 您可以将验证列表应用于整个范围。 Just expand the range to suit your needs. 只需扩大范围即可满足您的需求。

The following code is very basic and serves as an example. 以下代码是非常基本的示例。 For the example I chose col A through C to be filled with validation lists, from row 1 to the last filled row in column C. 对于该示例,我选择从A行到C行填充验证列表,从第1行到C列的最后一个填充行。

Sub FillRangeWithValidationLists()
Dim ws As Worksheet, rng As Range
Dim lrow As Long

Set ws = ActiveSheet 'not recommended to use the active sheet
Set ws = ThisWorkbook.Sheet1 'this would be a better method
lrow = ws.Cells(ws.Rows.Count, "C").End(xlUp).Row 'last row in column C 
Set rng = ws.Range("A1:C" & lrow) 'populate the rng variable with range you want

With rng.Validation
    .Delete
    .Add Type:=xlValidateList, _
    AlertStyle:=xlValidAlertStop, _
    Operator:=xlBetween, _
    Formula1:="=Table2"
    .ErrorMessage = "Please select January until December from the list"
End With

End Sub

Just change (ofc change Sheet1 for your sheet name) 只需更改(将工作表名称更改为off Sheet1)

 lastRow = sheets("Sheet1").cells(rows.count,1).end(xlup).row

 Formula1:="=Sheet1!A1:A"&lastRow

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM