【问题标题】:Run-Time Error 1004 Accessing Worksheet Function in VBA with Error Handling运行时错误 1004 在具有错误处理的 VBA 中访问工作表函数
【发布时间】:2023-01-27 03:32:50
【问题描述】:

下面提供的代码旨在突出显示否定词在关键字的 4 个词以内的单元格。为了我的恩人的隐私,我不会提供我搜索的关键字,但是你可以看到代码的功能。您可以将任何词作为测试的关键词,包括但不限于“Micheal”、“building”、“damage”等。在关键词匹配中使用工作表应用搜索的原因是为了确保这些词是复数不要不加标记。我遇到的问题是,当我运行代码时,如果 Temp 字符串中包含的单个单词与提供的关键字不匹配,它就会停止。我需要它做的是,如果临时字符串中的单个单词与关键字不匹配,那么 for 循环应该转到下一个第 j 个关键字。一些帮助将不胜感激。错误处理对我来说是陌生的领域。

Sub IdentifyCameraPresence()
    Application.ScreenUpdating = False
    
    Dim Rng As Range
    Dim x As Double, y As Double, i As Double
    Dim Negatives As Variant, Keys As Variant, n As Double, k As Double 'keeps track of the location of negatives and key words in a cell
    Dim NWords As Variant, KWords As Variant, m As Double, j As Double 'keeps track of the words that are negative and key
    Dim Temp As Variant
    
    Set Negatives = CreateObject("System.Collections.ArrayList")
    Set Keys = CreateObject("System.Collections.ArrayList")
    
    Set NWords = CreateObject("System.Collections.ArrayList")
    NWords.Add "no"
    NWords.Add "not"
    Debug.Print NWords(0); NWords.Count
    
    Set KWords = CreateObject("System.Collections.ArrayList")
    KWords.Add "key1"
    KWords.Add "key2"
    KWords.Add "key3"
    KWords.Add "key4"
    KWords.Add "key5"
    Debug.Print KWords(3)

    For Each Rng In Selection
        With Application.WorksheetFunction
            Temp = Split(Rng)
            For i = 0 To UBound(Temp)
            
                For m = 0 To NWords.Count - 1
                    If Temp(i) = NWords(m) Then Negatives.Add i
                Next m
'----------------------------PROBLEM IS HERE------------------------------------------------------------                
                For j = 0 To KWords.Count - 1
                    If .Search(KWords(j), Temp(i)) Then Keys.Add i
                Next j
'----------------------------PROBLEM IS HERE------------------------------------------------------------                  
            Next i
            
            For k = 0 To Keys.Count - 1
                For n = 0 To Negatives.Count - 1
                Debug.Print "Key"; Keys(k); "negative"; Negatives(n)
                    Debug.Print "In Color Index"
                    If Abs(Negatives(n) - Keys(k)) < 5 Then Rng.Interior.ColorIndex = 35
                Next n
            Next k
            
        End With
    Next Rng
    
    Application.ScreenUpdating = True
End Sub

【问题讨论】:

  • 您使用WorksheetFunction.Search 而不是InStr 有什么原因吗?
  • 解决了我的问题,谢谢。我现在已经让代码在某种程度上完美地工作了。

标签: excel vba error-handling worksheet-function


【解决方案1】:

不要使用WorksheetFunction.Search,考虑使用InStr

If InStr(Temp(i), KWords(j)) > 0 Then

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-12-06
    • 2016-03-25
    • 1970-01-01
    • 1970-01-01
    • 2018-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多