excel - 需要通过文本和数字组合找到最大值
问题描述
我在一列excel表中有一些数据。(文本-数字组合)喜欢:
AAA-32
BBB-54
AAA-221
CCC-05
DDD-212
文本总是 3 个字符长 & 后面总是跟着一个“ - ”,然后是一个数字。
我需要找到 AAA、BBB、CCC ..& 其他具有最大数量的文本的最大值。
AAA 的最大值是“AAA-221”,同样需要其他字符(BBB、CCC ..)
如何使用 VBA 实现它?
`Data is present in column A
'lRow = Last Row
`tchar contains no. of unique characters, here 4 (AAA,BBB,CCC,DDD)
Dim i as Integer, tchar as Integer, tArray() as String, rng as Range
'Copying unique characters from col A into col Z. (Ignore Cell A1, Z1)
Range("A2:A" & lRow).AdvancedFilter Action:=xlFilterCopy, CopyToRange:=Range("Z2"), Unique:=True
'To get tchar
Range("Z2").Select
Range(Selection, Selection.End(xlDown)).Select
tchar = Selection.Rows.Count
'Range with unique characters
Set rng = Range("Z2", "Z" & lRow)
'Re-Define array
ReDim tArray(tchar)
'Getting unique characters into array
For i = 1 To tchar
tArray(i) = rng.Item(i).Value
Next i
'Separated Text & Numbers into col B & C
'Col B has text (AAA,BBB...)
'Col C has numbers (32, 54, 221 ..)
'Now to use tArray() to traverse in col B & get max value from col C
'**I am stuck here**
解决方案
该任务看起来像是使用 Dictionary 对象的经典案例
Option Explicit
Sub SelectMax()
Dim Key As String, Value As Long, x As Variant, a As Variant, cnt As Long
Dim dict As Object: Set dict = CreateObject("Scripting.Dictionary")
With ThisWorkbook.Worksheets("Sheet1")
For Each x In Intersect(.Columns("A"), .UsedRange)
a = Split(x, "-")
Key = a(0): Value = Val(a(1))
If dict.exists(Key) Then
If Value > dict(Key) Then dict(Key) = Value
Else
dict.Add Key, Value
End If
Next
' output the result
Range("B1") = "Max" 'header
cnt = 1
For Each x In dict.Keys
Range("B1").Offset(cnt) = x & "-" & dict(x)
cnt = cnt + 1
Next
End With
End Sub
推荐阅读
- polymer - LitElement 生命周期:第一次渲染之前
- javascript - 如何使用 gl.readPixels 读取点大小 > 1 的绘制 gl.POINTS?
- makefile - 构建 AWS IoT 开发工具包时出现错误“源目录 ... 似乎不包含 CMakeLists.txt”
- java - 启用 ThriftParquetWriter 将 16 位整数写为短整数,而不是将其转换为 32 位整数
- python - 如何使全局变量在函数内部的 Spyder 中工作?
- laravel - 致命错误:已用完允许的 134217728 字节内存大小(尝试分配 53091665 字节)-Linode 服务器图像上传
- http - 如何在 POST 中的 JSON 中发送 JSON
- java - AIX - 无法创建 VM 线程。系统资源不足
- scala - 如何在 Play 框架的 Scala 模板中的 if 块中添加多个“OR”和“AND”条件
- llvm - 从分支指令中提取 MachineBasicBlock