使用VBA添加行时创建下拉列表

时间:2016-01-26 19:15:07

标签: excel vba excel-vba drop-down-menu

我想编写一个宏,其内容如下: 如果在A列下输入一个值,它会在B列的同一行中给出一个下拉列表。

我写了第一次有效的peice。但问题是当我运行它时,如果某些单元格中已经有一个下拉列表,它会中断!

Sub Macro2()
Dim cell As Range

'If a value is listed
  For Each cell In ActiveSheet.Range("A2:A1000")
    If cell.Value <> "" Then
        cell.Offset(0, 1).Select
        If Selection = Empty Then
            With Selection.Validation
                'add list box
                .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
                xlBetween, Formula1:="=Sheet1!A2:A20"
                .IgnoreBlank = True
                .InCellDropdown = True
                .InputTitle = ""
                .ErrorTitle = ""
                .InputMessage = ""
                .ErrorMessage = ""
                .ShowInput = True
                .ShowError = True
            End With
        End If
    End If
  Next cell
End Sub

我应该补充一点,我无法删除B列中的内容,因为我不想丢失已经存在的工作。

2 个答案:

答案 0 :(得分:2)

这是一个只删除验证,然后添加回来的解决方案。另外,我删除了.Select的使用,这可能会导致错误。

Dim isValid As Boolean

Sub Macro2()
Dim cell As Range

'If a value is listed
  For Each cell In ActiveSheet.Range("A2:A1000")
    If cell.Value <> "" Then
        testIfValidation cell.Offset(0, 1)
        If IsEmpty(cell.Offset(0, 1)) And Not isValid Then
            With cell.Offset(0, 1).Validation
                'add list box
                .Add Type:=xlValidateList, AlertStyle:=xlValidAlertStop, Operator:= _
                xlBetween, Formula1:="=Sheet1!A2:A20"
                .IgnoreBlank = True
                .InCellDropdown = True
                .InputTitle = ""
                .ErrorTitle = ""
                .InputMessage = ""
                .ErrorMessage = ""
                .ShowInput = True
                .ShowError = True
            End With
        End If
    End If
  Next cell
End Sub

Private Sub testIfValidation(ByVal cel As Range)
Dim X As Variant
On Error Resume Next
X = cel.Validation.Type
On Error GoTo 0
If IsEmpty(X) Then
    Debug.Print cel.Address & " has no validation"
    isValid = False
Else
    isValid = True
End If
End Sub

我通过测试更新了这个,以查看单元格是否有验证。如果是的话,它会跳过它。否则,照常进行。

答案 1 :(得分:0)

为什么在添加新数据之前不清除现有数据验证?

沿着这些方向:

        With Selection.Validation
            ' delete existing
            .Delete
            'add list box
            .Add Type etc.

Validation.Delete与点击&#34;全部清除&#34;相同。在数据验证对话框中。没有更改或删除单元格内容。

enter image description here

相关问题