vba - 以编程方式从 Excel 下拉列表中选择

标签 vba list excel

我想编写一个宏,该宏将从下拉列表(在我的例子中,在单元格 D6 中)中选择特定值(在我的例子中,存储在单元格 A1 中) >).

这是我到目前为止所拥有的:

sr_par2 = Array ("TEXT", 'TEXT2", "TEXT3")

sr = Range("A1").Value

(...)

Dim i As Integer
i = 0
Range("D6").Select

Do While (sr <> ActiveCell.FormulaR1C1)
    Range("D6").Select
    ActiveCell.FormulaR1C1 = sr_par2(i)
    i = i + 1
Loop

最佳答案

这就是你正在尝试的吗?我已经对代码进行了注释,这样您就不会在理解它时遇到问题。不过,如果您这样做,只需询问即可:)

Sub Sample()
    Dim ws As Worksheet
    Dim rngIn As Range, rngOut As Range
    Dim MyAr
    Dim sFormula As String
    Dim i As Long

    '~~> Replace this with the relevant worksheet
    Set ws = ThisWorkbook.Sheets("Sheet1")

    With ws
        '~~> Set your input and output range here
        Set rngIn = .Range("A1")
        Set rngOut = .Range("D6")

        '~~> Get the validation list if there is one
        On Error Resume Next
        sFormula = rngOut.Validation.Formula1
        On Error GoTo 0

        If sFormula = "" Then
            '~~> If no validation list then directly populate the value
            rngOut.Value = rngIn.Value
        Else
            'validation list TEXT1,TEXT2,TEXT3
            MyAr = Split(sFormula, ",")

            '~~> Loop through the list and compare
            For i = LBound(MyAr) To UBound(MyAr)
                If UCase(Trim(rngIn.Value)) = UCase(Trim(MyAr(i))) Then
                    rngOut.Value = MyAr(i)
                    Exit For
                End If
            Next i

            '~~> Check if the cell is still blank. If it is then it means that
            '~~> Cell A1 has a value which is not part of the list
            If Len(Trim(rngOut.Value)) = 0 Then
                MsgBox "The value in " & rngOut.Address & _
                " cannot be set as the value you are copying is not part of the list"
            End If
        End If
    End With
End Sub

关于vba - 以编程方式从 Excel 下拉列表中选择,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30523729/

相关文章:

excel - 如何在VBA excel中定义误差条的数量

vba - 删除列中所有有错误的行

Pythonic 循环列表

python - 如何将数据框变成一系列列表?

Java,向列表添加一个值<pair>

vba - 在 VBA 中,当范围中多个单元格包含一个值时,我想创建一个 If 语句

vba - 运行打开文件并将其另存为值的宏的宏 - 运行时错误 1004

excel - 根据里程碑/任务/子任务创建动态编号列表

excel - 想在 VBA 中创建多个 if 语句

android - Java中如何判断Excel文件的格式?