下拉列表中的默认值

时间:2012-12-23 15:34:11

标签: excel-vba excel-2003 vba excel

我想知道是否有人可以帮助我。

我正在使用下面的代码,在执行的许多操作中,自动使用日期填充“A”列,并在“a”中创建新记录时使用文本值“No”填充“AS”列Excel电子表格。

Option Explicit
Public preValue As Variant
Private Sub Worksheet_Change(ByVal Target As Range)

    Dim Cell As Range, res As Variant
    Dim rCell As Range
    Dim Rng1 As Range
    Dim Rng2 As Range
    Dim Rng3 As Range


    Application.EnableCancelKey = xlDisabled
    'Sheets("Input").Protect "handsoff", UserInterFaceOnly:=True, AllowFiltering:=True, AllowFormattingColumns:=True

    If Target.Column = 3 Then
        If Target = "No" Then MsgBox "Please remember to make the same change to all rows for " & Target.Offset(0, -1).Value & " and delete any future forecasts"
    End If

       If Target.Cells.Count > 1 Then Exit Sub
    On Error Resume Next

    If Not Intersect(Target, Range("B5:AD400", "AF5:AQ400")) Is Nothing Then
        If Target.Value <> preValue And Target.Value <> "" Then
            Application.EnableEvents = False
           With Rows(Target.Row)
                    .Range("A1").Value = Date
                    .Range("AS1").Value = "No"
        End With
            Application.EnableEvents = True
            Target.Interior.ColorIndex = 35
        End If
    End If

    On Error GoTo 0
    If Target.Column = 45 Then
                If Target.Value = "Yes" Then
                Set Rng1 = Application.Union(Cells(Target.Row, "B").Resize(, 19), Cells(Target.Row, "R"))
                Rng1.Interior.ColorIndex = xlNone
                Set Rng2 = Application.Union(Cells(Target.Row, "S").Resize(, 12), Cells(Target.Row, "AD"))
                Rng2.Interior.ColorIndex = 37
                Set Rng3 = Application.Union(Cells(Target.Row, "AF").Resize(, 12), Cells(Target.Row, "AQ"))
                Rng3.Interior.ColorIndex = 42
                End If
    End If

    If Not Intersect(Target, Range("J7:J400")) Is Nothing Then
        Set Cell = Worksheets("Lists").Range("B2:C23")
        res = Application.VLookup(Target, Cell, 2, False)
    If IsError(res) Then
        Range("K" & Target.Row).Value = ""
    Else
        Range("K" & Target.Row).Value = res
    End If
    End If

End Sub

我想做的是,如果可能的话,将日期插入“A”列,我想在“C”列的同一行插入文本值“Select”。此值取自我在下拉菜单中的第一个值,设置在名为“Lists”的工作表上,命名范围为“RDStaff”。

有人可能会告诉我如何更改功能,以便在列“A”填充日期后,列表中的第一个值即“选择”将自动填充到“C”列中“?

非常感谢和亲切的问候

克里斯

1 个答案:

答案 0 :(得分:1)

目前尚不清楚C列中哪个单元格正在使用验证列表的位置,但是如果将下面的代码添加到with语句中,它当然应该适用于适当的下拉单元格。

.Range("C1").Value = Sheets(1).Range("C10").Value

现在,假设您的下拉列表基于您的验证位于单元格C10中工作簿的第一张(按索引)。您需要调整这些以匹配您的数据/工作簿结构。

关键是你不要对值进行硬编码。您可以从下拉列表位置引用该值。

根据您的评论,这是一个代码片段,用于将验证列表添加到您的代码中。

With Rows(Target.Row)

    '... your existing code
    With Range("C1").Validation
      .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:=xlBetween,  Formula1:=Lists!RDStaff ' you may need to make this named range global for it to work on another sheet in this context
      .IgnoreBlank = True
      .InCellDropdown = True
    End With

End WIth