我在一列中有数字字符串,每个单元格包含从1到n的序列,序列由空格分隔。
1001
2034 2034 2034
3456 3456 3456 是否有一种方法可以计算每个单元中存在多少唯一的序列,并将这个数字放置在相邻的单元中?
因此,例如。
Column 1 Column 2
1001 1
2034 2034 2034 1
3456 3456 3456 1
3455 3455 5674 2
1234 3456 3456 4568 6754 4因此,我已经设法到了这一点,但我如何进行范围和循环,基本上打印结果到每个单元格(向右)的分析范围?
Sub CountStuff()
Dim c As Collection
Set c = New Collection
ary = Split(ActiveCell.Value, " ")
On Error Resume Next
For Each a In ary
c.Add a, CStr(a)
Next a
On Error GoTo 0
Debug.Print c.Count
End Sub发布于 2021-06-02 04:39:18
计数唯一子字符串(UDF)
函数
Option Explicit
Function CountUniqueSubStrings( _
ByVal SplitString As String, _
Optional ByVal Delimiter As String = " ") _
As Long
Dim SubStrings() As String: SubStrings = Split(SplitString, Delimiter)
Dim ssCount As Long: ssCount = UBound(SubStrings)
Dim usCount As Long
If ssCount < 1 Then
usCount = ssCount + 1
Else
Dim dict As Object: Set dict = CreateObject("Scripting.Dictionary")
Dim cString As String
Dim n As Long
For n = 0 To ssCount
cString = SubStrings(n)
If Len(cString) > 0 Then
dict(SubStrings(n)) = Empty
End If
Next n
usCount = dict.Count
End If
CountUniqueSubStrings = usCount
End FunctionExcel示例
=CountUniqueSubStrings(A1)VBA示例
Sub CountUniqueSubStringsTEST()
' Define constants.
Const sFirst As String = "A2"
Const dFirst As String = "B2"
Const Delimiter As String = " "
' Create a reference to the worksheet.
Dim ws As Worksheet: Set ws = ActiveSheet
' Maybe better examples:
'Set ws = Sheet1
'Set ws = ThisWorkbook.Worksheets("Sheet1")
' Create a reference to the Source Column Range.
Dim srg As Range
Dim rCount As Long
With ws.Range(sFirst)
Dim lCell As Range
Set lCell = .Resize(.Worksheet.Rows.Count - .Row + 1) _
.Find("*", , xlFormulas, , , xlPrevious)
If fCell Is Nothing Then Exit Sub
rCount = lCell.Row - .Row + 1
Set srg = .Resize(rCount)
Debug.Print srg.Address
End With
' Write values from the Source Column Range to the Data Array.
Dim Data As Variant
If rCount = 1 Then ' one cell only
ReDim Data(1 To 1, 1 To 1): Data(1, 1) = srg.Value
Else
Data = srg.Value
End If
' Replace the values in the Data Array with the 'unique counts'.
Dim r As Long
For r = 1 To rCount
Data(r, 1) = CountUniqueSubStrings(Data(r, 1), Delimiter)
Next r
' Create a reference to the Destination Column Range.
Dim drg As Range: Set drg = ws.Range(dFirst).Resize(rCount)
' Write the 'unique counts' from the Data Array
' to the Destination Column Range.
drg.Value = Data
' Clear the contents below the Destination Column Range.
With drg.Cells(1)
.Resize(.Worksheet.Rows.Count - .Row - rCount + 1) _
.Offset(rCount).ClearContents
End With
End Subhttps://stackoverflow.com/questions/67796091
复制相似问题