我是excel宏的新手,我需要创建一个excel宏,它将检查单元格中数字的前4个字符,如果它匹配不同列中单元格中的其他4个字符,则表示单独的列需要汇总在一起,并且在第一个实例中放置两个数字匹配的名为LE Internal的不同列。
答案 0 :(得分:1)
试试这个:
Sub Demo()
Dim dict1 As Object
Dim c1 As Variant, k As Variant
Dim currWS As Worksheet
Dim i As Long, lastRow As Long, tot As Long
Dim number1 As Long, number2 As Long, firstRow As Long
Set dict1 = CreateObject("Scripting.Dictionary")
Set currWS = ThisWorkbook.Sheets("Sheet2") '-->change Sheet1 to your work sheet name
'get last row withh data in Column A
lastRow = currWS.Cells(Rows.count, "A").End(xlUp).Row
'put unique numbers in Column A in dict1
c1 = Range("A2:B" & lastRow)
For i = 1 To UBound(c1, 1)
If c1(i, 1) <> "" Then
'make combination with first 4 characters
dict1(Left(c1(i, 1), 4) & "," & Left(c1(i, 2), 4)) = 1
End If
Next i
'loop through all the numbers in column A
For Each k In dict1.keys
number1 = Split(k, ",")(0)
number2 = Split(k, ",")(1)
tot = 0
firstRow = 0
For i = 2 To lastRow
If k = Left(currWS.Range("A" & i).Value, 4) & "," & Left(currWS.Range("B" & i).Value, 4) Then
If firstRow = 0 Then
firstRow = i
End If
tot = tot + currWS.Range("C" & i).Value
End If
Next i
currWS.Range("D" & firstRow) = tot
Next k
End Sub
见图片参考: