【问题标题】:a way to find a string within merged cells一种在合并单元格中查找字符串的方法
【发布时间】:2019-06-27 22:47:55
【问题描述】:

我需要在目录中的文件中搜索字符串的出现并返回计数。

为了进行测试,我将 4 个工作簿和 5 个工作表放入 C:\test 目录。我正在寻找工作簿中任何地方出现氨这个词的计数。我正在使用的代码正在重新调整“0”,即使我确定它存在。我相信它是因为lookin 不适用于合并的单元格。有什么技巧可以让这项工作发挥作用吗?

Sub LoopThroughFiles()
Range("'sheet1'!A6:M10000").ClearContents

Dim directory As String, fileName As String, sheet As Worksheet, i As Integer, j As Integer
directory = "C:\Test\"
fileName = Dir(directory & "*.xl??")



i = 5
Do While fileName <> ""

i = i + 1

If fileName <> "" Then
Dim wbk As Workbook
With wbk
Set wbk = Workbooks.Open(directory & fileName)
End With


Dim sh As Worksheet
Dim found As Range
Dim count As Integer

For Each sh In wbk.Worksheets
    Set found = sh.Cells.Find(what:="Ammonia", LookIn:=xlFormulas)


    If Not found Is Nothing Then
       sh.Activate
       found.Select
        count = count + sh.Range(found.Address).Offset(0, 3).Value
       Else
    End If
Next sh
wbk.Close
End If



fileName = Dir()

Loop

Range("'Sheet1'!C2").Value = count

End Sub

代码未在合并单元格中找到值。

【问题讨论】:

  • 这可能与LookIn:=xlFormulas 有关。你试过xlValues吗?

标签: excel vba


【解决方案1】:

欢迎来到 SO。

您提供的代码接近应有的代码。但是,它只会在每个工作表中找到一次。我不确定这是否是设计使然,因此在下面的代码中,我将演示如何找到每个工作表的所有匹配项。

另外,我不确定我是否理解您如何在每个循环中增加 count 的逻辑。目前,您的代码找到值为“Ammonia”的单元格,然后向右移动 3 个单元格并将任何值添加到 count。同样,我不确定这是否是设计使然。

另外,您不需要sh.Activate 和found.Select。

下面是我建议的代码,以及解释其工作原理的 cmets。

Option Explicit

Sub LoopThroughFiles()
'
' your code to loop through workbooks
'

Debug.Print numOfOccurrences("Ammonia", wbk) 'call the search function and print the number of occurrences to the immediate window

'
' your code continues
'

End Sub

Public Function numOfOccurrences(keyword As String, wb As Workbook) As Long

Dim sht As Worksheet
Dim found As Range
Dim count As Long
Dim firstOccurence As String
count = 0

For Each sht In wb.Worksheets 'loop through sheets
    Set found = sht.Cells.Find(what:=keyword) 'search for the first occurrence if any
    If Not found Is Nothing Then 'if the keyword is found once, then we need to search for more occurrences
        firstOccurence = found.Address 'store the address of the first occurence
        Do
            Set found = sht.Cells.FindNext(found) 'search for the next occurrence in the same sheet
            count = count + 1 'keep track of the number of occurences
        If found Is Nothing Then
            GoTo DoneFinding    'this deals with what seems to be a bug when using .FindNext with merged cells
        End If
        Loop Until found.Address = firstOccurence 'repeat until the search goes full circle back to the first occurrence
    End If
DoneFinding:
Next sht
numOfOccurrences = count

End Function

【讨论】:

  • 效果很好,非常感谢!
猜你喜欢
  • 2021-02-11
  • 2018-07-23
  • 1970-01-01
  • 2021-09-12
  • 1970-01-01
  • 1970-01-01
  • 2020-02-20
  • 2014-07-22
相关资源
最近更新 更多