VBA语法错误,一张纸上有多个子

时间:2018-06-22 16:08:40

标签: excel vba excel-vba

我是VBA的新手,正在尝试创建一个在后台运行一些不同脚本的用户窗体。

我现在要堆叠的第一件事是一个组合框下拉列表,该列表框根据选择的内容隐藏了某些列。第二个是对命名范围的HasValidation检查,以防止用户复制粘贴到所述列中的数据。

当在单独的工作簿上运行时,这两个部分运行良好,但是第二个尝试将HasValidation添加到组合框选择中,但出现语法错误,我无法找到原因。

到目前为止我的想法: 在工作表中选择ANY单元格时出现语法错误,因此使我相信我可能未正确定位该范围。

我的Range总共大约有2400个单元格,所以也许我需要使用Enable.Events = False来容纳它。

这是代码


Private Sub Worksheet_Change(ByVal Target As Range)
    'Does the validation range still have validation?
    If HasValidation(Range("ValidationRange")) Then
        Exit Sub
    Else
        Application.Undo
        MsgBox "Your last operation was canceled." & _
        "It would have deleted data validation rules.", vbCritical
    End If
End Sub

Private Function HasValidation(r) As Boolean
'   Returns True if every cell in Range r uses Data Validation
    On Error Resume Next
    x = r.Validation.Type
    If Err.Number = 0 Then HasValidation = True Else HasValidation = False
End Function

Private Sub ComboBox1_Change()

'hide/unhide ifs. selection # = Module #
If Me.ComboBox1.Value = "Modify Access" Then
    Call selection_1
End If

If Me.ComboBox1.Value = "Remove Access" Then
    Call selection_2
End If

If Me.ComboBox1.Value = "Add/Update Access" Then
    Call selection_3
End If

If Me.ComboBox1.Value = "Team" Then
    Call selection_4
End If

If Me.ComboBox1.Value = "Team Change" Then
    Call selection_5
End If

If Me.ComboBox1.Value = "Request" Then
    Call selection_6
End If


'Initial/without a selection
Application.ScreenUpdating = False

If ComboBox1.Value = Null Or ComboBox1.Value = "" Then
    ComboBox1.BackStyle = fmBackStyleTransparent

    Worksheets("MUS Form").Range("D:R").EntireColumn.Hidden = True
    Worksheets("MUS Form").Range("T:BQ").EntireColumn.Hidden = True
Else
ComboBox1.BackStyle = fmBackStyleOpaque
End If

Application.ScreenUpdating = True

End Sub

谢谢

1 个答案:

答案 0 :(得分:1)

在您的HasValidation'helper'函数中,更改

If Err.Number = 0 Then HasValidation = True Else HasValidation = False

...到

HasValidation = cbool(Err.Number = 0)

别忘了重置错误控制并遍历整个范围。

Private Function HasValidation(rs as range) As Boolean
'   Returns True if every cell in Range r uses Data Validation
    dim r as range, x as long
    On Error goto err_control
    for each r in rs
        x = r.Validation.Type
    next r
    HasValidation = true
    on error goto 0
    exit function
err_control:
    HasValidation = false
    on error goto 0
End Function

将禁用事件添加到worksheet_change中,以使其不会尝试在自身之上运行。

Private Sub Worksheet_Change(ByVal Target As Range)
    'Does the validation range still have validation?
    If HasValidation(Range("ValidationRange")) Then
        Exit Sub
    Else
        application.enableevents = false
        Application.Undo
        MsgBox "Your last operation was canceled." & _
        "It would have deleted data validation rules.", vbCritical
        application.enableevents = true
    End If
End Sub