如何在vba中获取查找结果的计数

时间:2018-05-18 06:34:37

标签: vba excel-vba excel

我编写了一个代码来计算查找结果的出现次数,我面临的问题是。如果查找数据超过255个字符,代码返回计为'0'虽然我们有一些匹配,对于那些查找小于255的数据,代码正常工作并获取正确的计数。 任何人都可以纠正这个问题,下面是代码。

Sub CommentCount()

Dim CSAT_Comments As Workbook
Dim comment As Worksheet
Dim match As Worksheet
Dim CommentString As String
Dim MatchRow As Integer


Set CSAT_Comments = ActiveWorkbook
Set comment = CSAT_Comments.Worksheets("Qualitative Analysis_2018 Cycle") 
Set match = CSAT_Comments.Worksheets("Consolidated Comments") 

Dim CommentRange As Range
match.Range("A2").Select
Dim CRange As Range
Dim DuplicateCount As Integer

Set CommentRange = match.Range(Selection, Selection.End(xlDown)) 'Defining the range

For Each CRange In CommentRange.SpecialCells(xlCellTypeVisible)


CommentString = Left(CRange.Value, 255) 'Store the first 225 characters of the string
MatchRow = CRange.Row 'To get the row number of the respective comments


With comment

Application.ScreenUpdating = False

.Activate
Columns("AK:BL").Select 'Range which needs to be searched

DuplicateCount = Application.WorksheetFunction.CountIf(Range("AK:BL"), "" & CommentString) ' To get the count of find result and here is where i am getting the problem when the search string is >255


With match
.Activate
.Range("B" & MatchRow) = DuplicateCount 'Paste the count in the against respective commments

End With

End With



Next CRange


End Sub

1 个答案:

答案 0 :(得分:1)

使用

CommentString = Left(CRange.Value, 254) & "*" 'Store the first 254 characters of the string, leaving the 255th character for final asterisk