用VBA实现下面的业务:1. 对M列,从M6单元格开始,到最大的行数的单元格区间的每一个单元格,按字符/分割单元格内的字符串,形成字符数组arri, 2. 遍历数组arri,若数组元素的值在名为xxx工作簿的A列里,则设置该值为N列对应行的值,
时间: 2023-05-24 15:05:10 浏览: 211
VBA 按照某一列进行筛选拆分数据,拆分成多个表或多个Sheet,按某列检查重复生成新的Sheet,删除除本表外的所有表
5星 · 资源好评率100%
下面是实现上述业务的VBA代码:
Sub SplitAndMatch()
Dim lastRow As Long
Dim i As Long, j As Long
Dim arri As Variant
Dim ws As Worksheet
Dim ws1 As Worksheet
Dim arrA As Variant
Dim arrN As Variant
Dim found As Boolean
Set ws = ActiveSheet '或者指定要处理的工作表,比如Set ws = Worksheets("Sheet1")
Set ws1 = Workbooks("xxx.xlsx").Worksheets("Sheet1") '指定要匹配的工作簿和工作表
'获取M列最大行数
lastRow = ws.Cells(ws.Rows.Count, 13).End(xlUp).Row
'循环处理每一行
For i = 6 To lastRow
'按/分割M列单元格内字符串成数组
arri = Split(ws.Cells(i, 13).Value, "/")
'遍历数组arri
For j = LBound(arri) To UBound(arri)
'在xxx工作簿的A列中查找当前数组元素的值,找到则设置N列对应行的值
arrA = ws1.Range("A1", ws1.Cells(ws1.Rows.Count, 1).End(xlUp)).Value
arrN = ws.Range("N1", ws.Cells(ws.Rows.Count, 14).End(xlUp)).Value
found = False
For k = LBound(arrA) To UBound(arrA)
If arrA(k, 1) = arri(j) Then
arrN(i, 1) = arrA(k, 1)
found = True
Exit For
End If
Next k
If Not found Then
arrN(i, 1) = ""
End If
Next j
Next i
'将结果写入N列
ws.Range("N1", ws.Cells(lastRow, 14)).Value = arrN
End Sub
上述代码中,我们首先获取了M列最大行数,然后对于每一行,按/分割M列单元格内字符串成数组,然后遍历数组arri,按照在xxx工作簿的A列中查找当前数组元素的值的方式,找到则设置N列对应行的值,最后将结果写入N列。注意,上述代码中的xxx.xlsx和Sheet1需要根据实际情况进行修改。
阅读全文