本帖最後由 s20012797 於 2024-6-28 21:10 編輯
- Sub ExtractAndGroupValues()
- Dim df As Variant
- Dim dfExtracted As Variant
- Dim dfMax As Variant
- Dim i As Long
- Dim substring As String
- Dim value As Long
-
- ' Assume your data is in the range "A1:A6" on the "Sheet1" worksheet
- df = Worksheets("Sheet1").Range("A1:A6").Value
-
- ' Initialize the new dataframe
- ReDim dfExtracted(1 To UBound(df), 1 To 2)
-
- ' Process each row of data one by one
- For i = 1 To UBound(df)
- ' Extract the substring and value
- substring = Extract_Substring(df(i, 1))
- value = Extract_Value(df(i, 1))
-
- ' Store the extracted values in the new dataframe
- dfExtracted(i, 1) = substring
- dfExtracted(i, 2) = value
- Next i
-
- ' Group by the substring and find the maximum value
- dfMax = GroupAndFindMax(dfExtracted)
-
- ' Display the result on the "Sheet2" worksheet
- Worksheets("Sheet2").Range("A1").Resize(UBound(dfMax), 2).Value = dfMax
- End Sub
- Function Extract_Substring(input As String) As String
- Dim match As Object
- Dim regEx As Object
-
- Set regEx = CreateObject("VBScript.RegExp")
- regEx.Pattern = "([a-zA-Z]+)(\d+)"
-
- Set match = regEx.Execute(input)
- If match.Count > 0 Then
- Extract_Substring = match(0).SubMatches(0)
- Else
- Extract_Substring = ""
- End If
- End Function
- Function Extract_Value(input As String) As Long
- Dim match As Object
- Dim regEx As Object
-
- Set regEx = CreateObject("VBScript.RegExp")
- regEx.Pattern = "([a-zA-Z]+)(\d+)"
-
- Set match = regEx.Execute(input)
- If match.Count > 0 Then
- Extract_Value = CLng(match(0).SubMatches(1))
- Else
- Extract_Value = 0
- End If
- End Function
- Function GroupAndFindMax(data As Variant) As Variant
- Dim result As Variant
- Dim dict As Object
- Dim key As Variant
- Dim maxValue As Long
- Dim i As Long
-
- ' Initialize the result
- ReDim result(1 To 0, 1 To 2)
-
- ' Create a dictionary to group and find the maximum value
- Set dict = CreateObject("Scripting.Dictionary")
-
- ' Process each row of data
- For i = 1 To UBound(data)
- key = data(i, 1)
- If dict.Exists(key) Then
- If data(i, 2) > dict(key)(2) Then
- dict(key) = Array(key, data(i, 2)) ' Fix: Store the value in the second column
- End If
- Else
- dict.Add key, Array(key, data(i, 2))
- End If
- Next i
-
- ' Store the result in the new dataframe
- i = 1
- For Each key In dict.Keys
- ReDim Preserve result(1 To i, 1 To 2)
- result(i, 1) = dict(key)(0) ' Fix: Store the key in the first column
- result(i, 2) = dict(key)(1)
- i = i + 1
- Next key
-
- GroupAndFindMax = result
- End Function
複製代碼 你確定vba 使用範圍太窄???
 |