-2
我是新来的excel宏,我需要创建一个excel宏,它将检查单元格中数字的前4个字符,如果它匹配其他4个字符放在不同列中的单元格中,那么需要将单独列中的值相加在一起,并放在第一个实例中,这两个数字匹配到名为LE Internal的不同列中。创建excel宏来检查列值并将它们相加
我是新来的excel宏,我需要创建一个excel宏,它将检查单元格中数字的前4个字符,如果它匹配其他4个字符放在不同列中的单元格中,那么需要将单独列中的值相加在一起,并放在第一个实例中,这两个数字匹配到名为LE Internal的不同列中。创建excel宏来检查列值并将它们相加
试试这个:
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
见图片供参考:
谢谢你,有没有改变的一种方式代码只查看c的前4个字符列A和列B?例如,如果数字1的数字是12434,列b的数字是12434,那么它只会查找1243? –
@GeorgeHalford - 使用'Set rFound = .Find(What:= Left(k,4)&“*”,LookIn:= xlValues,LookAt:= xlWhole)'Set rFound = .Find(What:= k ,LookIn:= xlValues,LookAt:= xlWhole)' – Mrig
@GeorgeHalford - 你能展示一些样本数据和期望的输出。我将能够更好地回答。 – Mrig