【问题标题】:Setting the name of cells inside a vba function在 vba 函数中设置单元格的名称
【发布时间】:2014-12-09 15:38:21
【问题描述】:

在 VBA 函数中,我尝试更改某些单元格的名称以标记它们并在以后使用它们。我有一个搜索功能,可以从 .txt 文件中搜索 excel 文档中的关键字,并且需要知道哪些单元格不包含任何搜索词。为此,我将命名我查询的每个单元格,并将所有未命名的单元格包含在“其他”的结果列中。但是,每当我尝试命名一个单元格时,名称都不会更新。我尝试了以下方法:

ThisWorkbook.Names.Add "QUERIED", RefersTo:=foundRange

foundRange.name = "已查询"

函数在这里:

Function Single_word_occurrences(datatoFind As String, resultsCol As String) As Integer
    'Initializations
    Dim strFirstAddress As String
    Dim foundRange As Range
    Dim currentSheet As Integer, sheetCount As Integer, LastRow As Integer, loopedOnce As Integer, FoundCount As Integer

    FoundCount = 0
    currentSheet = ActiveSheet.Index
    sheetCount = ActiveWorkbook.Sheets.Count

    Sheets("Sheet1").Activate
    Set foundRange = Range("F2:F30000").Find(What:=datatoFind, After:=Cells(2, 6), LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False)
    Sheets("List Results").Cells(1, resultsCol).Value = datatoFind
    'if datatoFind is found in search range
    If Not foundRange Is Nothing Then
        'save the address of the first occurrence of datatoFind, in the strFirstAddress variable
        strFirstAddress = foundRange.Address
        Do
            'Find next occurrence of datatoFind
            Set foundRange = Range("F2:F30000").Find(What:=datatoFind, After:=foundRange.Cells, LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, SearchDirection:=xlNext, MatchCase:=False)
            'Place the value of this occurrence in the next cell down in the column that holds found values (resultsCol column of List Results worksheet)
            LastRow = Sheets("List Results").Range(resultsCol & Rows.Count).End(xlUp).Row + 1
            Sheets("List Results").Range(resultsCol & LastRow).Value = foundRange.Address
            ThisWorkbook.Names.Add "QUERIED", RefersTo:=foundRange
            If loopedOnce = 1 Then
                FoundCount = FoundCount + 1
            End If
            If loopedOnce = 0 Then
                loopedOnce = 1
            End If
            'The Loop ends on reaching the first occurrence of datatoFind
        Loop While foundRange.Address <> strFirstAddress And Not foundRange Is Nothing
        Msgbox(foundRange.Name)
    End If
    Single_word_occurrences = FoundCount
    Application.ScreenUpdating = True
    Sheets(currentSheet).Activate
End Function

【问题讨论】:

    标签: vba excel naming names


    【解决方案1】:

    您不能在 UDF

    中定义名称

    您必须使用

    以下将失败:

    Public Function qwerty(r As Range) As Variant
        qwerty = 1
        Range("B9").Name = "whatever"
    End Function
    

    【讨论】:

    • 谢谢,我不知道。那么,您认为我应该如何标记找到的单元格以匹配我的查询?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-09-18
    • 1970-01-01
    • 2013-09-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多