【问题标题】:Run-time error 91 using Worksheet_SelectionChange使用 Worksheet_SelectionChange 的运行时错误 91
【发布时间】:2022-07-13 05:40:23
【问题描述】:

SelectionChange 事件对选择范围有任何限制吗?在第一行“ClickCol”标题下的单元格上选择后,我在执行简单范围选择时遇到运行时错误。

Private Sub Worksheet_SelectionChange(ByVal Target As Excel.Range)
    Dim shelvesSht As Worksheet
    Set shelvesSht = ActiveSheet
    Dim selectionRange As Range
    If ActiveSheet.Cells(1, ActiveCell.Column).Value = "ClickCol" Then 
        Dim headerRow As Long
        headerRow = 1
        selectionRange = shelvesSht.Cells(1, 1)  '<--- Here is where I get the error
        MsgBox "Selected cell in Click Col... Moving on"
    End If
End Sub

此后我的目标是选择整个第一行 selectionRange.EntireRow.Select 然后使用此选择来查找各种标题的列号。

【问题讨论】:

    标签: excel select event-handling runtime-error


    【解决方案1】:

    好的,我回答了我自己的问题,这就是解决方案。我认为该事件正在创建一个导致错误的循环。以这种方式使用错误处理似乎解决了我在这个项目中的所有问题:

    Private Sub Worksheet_SelectionChange(ByVal Target As Excel.Range)
        Dim selectionRange As Range
        Dim itypename As String
        If ActiveSheet.Cells(1, ActiveCell.Column).Value = "Search" Then 'ActiveCell.Column = 10 Then
            'MsgBox "Active Sheet / Selected Sheet Name: " & ActiveSheet.Name
            On Error GoTo ErrHandler
            Application.EnableEvents = False
            selectionRange = Worksheets(ActiveSheet.Name).Range("A1").EntireRow.Select
            selectionRange.Activate
    ErrHandler:
            Application.EnableEvents = True
            'MsgBox "Moving Forward"
       
            Dim rng As Range
            Set rng = Selection.Find(What:="Description", After:=ActiveCell, LookIn:=xlFormulas, _
                LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:= _
                False, SearchFormat:=False)
            If Not rng Is Nothing Then 'when rng <> nothing means found something'
                rng.Activate
                'MsgBox "Desc Column: " & rng.Column
                itypename = ActiveSheet.Cells(Target.Row, rng.Column).Value
                
            Else
                MsgBox "Did not find Description header"
                Exit Sub
            End If
    

    如果您能更清楚地说明这一点,请随时在 cmets 中做笔记。

    谢谢。

    【讨论】:

      猜你喜欢
      • 2011-09-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-25
      • 2013-04-16
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多