Как вернуть ссылку на ячейку для ячейки, содержащей определенный комментарий? - PullRequest
0 голосов
/ 25 апреля 2019

Я написал подпрограмму VBA для поиска в комментариях (теперь называемых заметками) листа Excel определенной текстовой строки. Я хочу, чтобы код возвращал адрес (т.е. ссылку на ячейку) ячейки, содержащей определенный комментарий. Однако написанный код, похоже, возвращает значение в ячейке, а не адрес ячейки.

Я пытался изменить строку:

Set RefCell = cmt.Parent

в следующем коде, чтобы:

Set RefCell = cmt.Parent.Address

согласно другому решению, которое я нашел. Однако это приводит к ошибке времени выполнения «424» «Требуется объект».

Я ценю любую помощь, которую может оказать каждый.

Public Sub CommentLocator(Sht As Worksheet, RefCell As Range, CommentID As String)

    Dim Message As String, Title As String

    Dim cmt As Comment

    'On Error GoTo ErrorTrap

    'Clear previous value of RefCell
    Set RefCell = Nothing

    'Searches all comments on the worksheet for specific text string _
    and returns the range of the parent cell
    For Each cmt In Sht.Comments
        If cmt.Text = CommentID Then
            Set RefCell = cmt.Parent
            Exit Sub
        End If
    Next cmt

    If RefCell Is Nothing Then

        'Display error message
        Message = "Error!" & vbCrLf & _
            "No viable comments found on sheet '" & Sht.Name & "'" & vbCrLf & vbCrLf & _
            "Seek technical assistance."
        Title = "Error"

        MsgBox Message, vbExclamation + vbOKOnly, Title

    End If

Exit Sub

Я ожидаю, что RefCell возвратит ссылку / адрес ячейки, но вместо этого он возвращает значение в ячейке.

Ответы [ 3 ]

1 голос
/ 25 апреля 2019

Вам нужно использовать RefCell.Address, чтобы получить ссылку на ячейку.Использование Set в этой строке Set RefCell = cmt.Parent.Address предполагает Object, но вместо этого вы передаете String, поэтому вы получаете сообщение об ошибке

Попробуйте вместо этого следующее:

If RefCell Is Nothing Then
    'Display error message
    Message = "Error!" & vbCrLf & _
        "No viable comments found on sheet '" & Sht.Name & "'" & vbCrLf & vbCrLf & _
        "Seek technical assistance."
    Title = "Error"

    MsgBox Message, vbExclamation + vbOKOnly, Title
Else
    MsgBox RefCell.Address
End If
0 голосов
/ 21 мая 2019

Решено.

По сути, моя проблема заключалась в том, что я определял свою переменную как диапазон, когда она должна была быть строкой.

Спасибо тем, кто прокомментировал - вы былиМне очень полезно прийти к этому решению.

Вот мое решение полностью:

'Require all variables to be declared
Option Explicit

'Public Variable Declarations
Public Message As String, Title As String


Public Sub CommentLocator(ByVal ObjectiveCommentID As String, _
           ByVal VariableCommentID As String, ByRef ObjectiveCell As String, _
           ByRef VariableCell As String)

    Dim cmt As Comment

    On Error GoTo ErrorTrap


    'Searches all comments on the active worksheet for specific text strings _
    represented by 'ObjectiveCommentID' and 'VariableCommentID' and returns the _
    addresses of the parent cells as strings
    For Each cmt In ActiveSheet.Comments
        If cmt.Text = ObjectiveCommentID Then
            ObjectiveCell = cmt.Parent.Address
        ElseIf cmt.Text = VariableCommentID Then
            VariableCell = cmt.Parent.Address
        End If
    Next cmt


    'Displays error message if no viable '$OBJECTIVE' comments found on sheet
    If ObjectiveCell = "" Then

        Message = "Runtime Error!" & vbCrLf & vbCrLf & _
            "No viable '" & ObjectiveCommentID & "' comments found on sheet" & vbCrLf _
            & "'" & ActiveSheet.Name & "'" & vbCrLf & vbCrLf & _
            "Check and update comments (notes) and try again."
        Title = "Error!"

        MsgBox Message, vbExclamation + vbOKOnly, Title

    End If


    'Displays error message if no viable '$VARIABLE' comments found on sheet
    If VariableCell = "" Then

        Message = "Runtime Error!" & vbCrLf & vbCrLf & _
            "No viable '" & VariableCommentID & "' comments found on sheet" & vbCrLf _
            & "'" & ActiveSheet.Name & "'" & vbCrLf & vbCrLf & _
            "Check and update comments (notes) and try again."
        Title = "Error!"

        MsgBox Message, vbExclamation + vbOKOnly, Title

    End If


Exit Sub


ErrorTrap:

    'Set calculation mode to auto & enable events
    Application.Calculation = xlCalculationAutomatic
    Application.EnableEvents = True

    'Enable screen updating & status bar
    Application.DisplayStatusBar = True
    Application.ScreenUpdating = True

    'Display error message
    Message = "Fatal Error!" & vbCrLf & _
        "Error in subroutine 'CommentLocator'." & vbCrLf & _
        "Seek technical assistance."
    Title = "Error!"

    MsgBox Message, vbExclamation + vbOKOnly, Title

End Sub
0 голосов
/ 25 апреля 2019

Вы можете использовать SpecialCells для просмотра всех ячеек с комментариями (примечаниями):

On Error Resume Next
Set CommentCells = ActiveSheet.Range("A1").SpecialCells(xlCellTypeComments)
On Error GoTo 0
If CommentCells Is Nothing Then
    Exit Sub
End If

Затем, чтобы делать с комментариями все, что вы хотите, переберите все ячейки с комментариями, используя:

For each RefCell in CommentCells
    'Do something 
Next RefCell
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...