|
楼主 |
发表于 2023-3-4 10:29
|
显示全部楼层
补上code
Sub TransformData()
Const SRC_FIRST_CELL As String = "A1"
Const DST_FIRST_CELL As String = "I1"
Const DATE_COL As Long = 1
Const HOUR_COL As Long = 2
Const WIND_COL As Long = 3
Const DH_DELIMITER As String = "|!|"
Const WIND_DELIMITER As String = "/"
Const COLUMNS_COUNT As Long = 3 ' fixed
Dim ws As Worksheet: Set ws = ActiveSheet ' improve!
Dim srg As Range: Set srg = ws.Range(SRC_FIRST_CELL).CurrentRegion
Dim srCount As Long: srCount = srg.Rows.Count
Dim dData(): dData = srg.Columns(DATE_COL).Value
Dim hData(): hData = srg.Columns(HOUR_COL).Value
Dim wData(): wData = srg.Columns(WIND_COL).Value
Dim dict As Object: Set dict = CreateObject("Scripting.Dictionary")
dict.CompareMode = vbTextCompare
Dim r As Long, dString As String, wString As String
For r = 2 To srCount
dString = dData(r, 1) & DH_DELIMITER & hData(r, 1)
If Not dict.Exists(dString) Then
Set dict(dString) = CreateObject("Scripting.Dictionary")
End If
wString = wData(r, 1)
dict(dString)(wString) = dict(dString)(wString) + 1
Next r
Dim drCount As Long: drCount = dict.Count + 1
Dim Data(): ReDim Data(1 To drCount, 1 To COLUMNS_COUNT)
Dim dLen As Long: dLen = Len(DH_DELIMITER)
Data(1, 1) = dData(1, 1)
Data(1, 2) = hData(1, 1)
Data(1, 3) = wData(1, 1)
r = 1
wString = ""
Dim oKey, iKey, dPos As Long, wMax As Long
For Each oKey In dict.Keys
r = r + 1
dPos = InStr(oKey, DH_DELIMITER) - 1
Data(r, 1) = CDate(Left(oKey, dPos))
Data(r, 2) = CLng(Right(oKey, Len(oKey) - dPos - dLen))
For Each iKey In dict(oKey).Keys
'Debug.Print r, oKey, iKey, dict(oKey)(iKey)
If dict(oKey)(iKey) > wMax Then
wString = iKey
wMax = dict(oKey)(iKey)
ElseIf dict(oKey)(iKey) = wMax Then
wString = wString & WIND_DELIMITER & iKey
End If
Next iKey
Data(r, 3) = wString
'Debug.Print Data(r, 1), Data(r, 2), Data(r, 3)
wMax = 0
wString = ""
Next oKey
With ws.Range(DST_FIRST_CELL).Resize(drCount, COLUMNS_COUNT)
.CurrentRegion.ClearContents
.Value = Data
End With
MsgBox "Data transformed.", vbInformation
End Sub
|
|