Excel VBA 宏:使用 Sheet1 中 ColumnA 的数据更新 Sheet2 上的验证列表

问题描述 投票:0回答:1

提前致谢。

我正在尝试将sheet1中A列的数据添加到sheet2中特定单元格的验证下拉列表中。 A 列中的数据长度将根据当天检索的数据而变化。我当前的代码调用了一个特定范围(例如“A2:A13”)。如何使用“Cells(Rows.Count, 1).End(xlUp).Row”在从columnAsheet1中选择范围时提供更大的灵活性?

以下是目前的:

'Select and update new AccessionGroups

Sub Update()

Dim WS As Worksheet
Dim WS2 As Worksheet

Set WS = Sheet1
Set WS2 = Sheet2

'lastrow = Worksheets(WS).Cells(Rows.Count, 1).End(xlUp).Row (**Trying to figure out how to use this)

WS2.Range("E9").Validation.Delete
WS2.Range("E9").Validation.Add xlValidateList, , ,"='" & WS.Name & "'!" & WS.Range("A2:A13").Address
     
WS2.Range("E10").Validation.Delete
WS2.Range("E10").Validation.Add xlValidateList, , ,"='" & WS.Name & "'!" & WS.Range("A2:A13").Address

WS2.Range("E11").Validation.Delete
WS2.Range("E11").Validation.Add xlValidateList, , ,"='" & WS.Name & "'!" & WS.Range("A2:A13").Address

End Sub

我从另一个网站获得了此代码,以符合我对该项目的目的。为什么xlValidateList有3个逗号

谢谢。

excel vba
1个回答
0
投票

你可以使用这样的东西:

Sub Update()

    Dim WS As Worksheet
    Dim WS2 As Worksheet
    Dim lastRow As Long
    Dim validationRange As String

    Set WS = Sheet1
    Set WS2 = Sheet2

    ' Determine the last row with data in column A of Sheet1
    lastRow = WS.Cells(WS.Rows.Count, 1).End(xlUp).Row

    ' Create the range string for data validation
    validationRange = "'Sheet1'!A2:A" & lastRow

    ' Update data validation for the specified cells in Sheet2
    With WS2.Range("E9").Validation
        .Delete
        .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
        xlBetween, Formula1:=validationRange
    End With

    With WS2.Range("E10").Validation
        .Delete
        .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
        xlBetween, Formula1:=validationRange
    End With

    With WS2.Range("E11").Validation
        .Delete
        .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
        xlBetween, Formula1:=validationRange
    End With

End Sub

为什么

xlValidateList
中有三个逗号?
Validation.Add
方法有几个参数,Type、AlertStyle、Operator、Formula1。逗号分隔这些参数,如果不需要参数,则将其留空,因此需要三个逗号。

© www.soinside.com 2019 - 2024. All rights reserved.