为了能够高效地执行此操作,您需要确保数据按以下方式排序:
-
Sales
-
linenum
-
Config
-
Part
它需要同时按所有 4 列按此顺序排序,否则您可能会得到混乱的数据!
还假设选项编号总是以相应的基数加破折号作为前缀。
然后我们将需要的列读入数组中(以加快处理速度)。我们逐行遍历该数据。当我们在配置中找到C 时,我们会记住该行号(用于比较X 选项和写入输出)。我们继续下一行并检查它是否是一个选项以及它是否属于 rembered 基本配置。如果是这样,我们将选项部分编号附加到基本配置。
最后我们将数组数据写回单元格。
Option Explicit
Public Sub GetFullConfigFromOptions()
Dim ws As Worksheet ' define your sheet here
Set ws = ThisWorkbook.Worksheets("Sheet1")
Dim LastRow As Long
LastRow = ws.Cells(ws.Rows.Count, "A").End(xlUp).Row
' read data columns into array
Dim ArrSalesNo() As Variant 'define Sales column
ArrSalesNo = ws.Range("A1").Resize(RowSize:=LastRow).Value
Dim ArrConfig() As Variant 'define Config column
ArrConfig = ws.Range("B1").Resize(RowSize:=LastRow).Value
Dim ArrPartNo() As Variant 'define Part column
ArrPartNo = ws.Range("C1").Resize(RowSize:=LastRow).Value
Dim ArrLineNo() As Variant 'define Linenum column
ArrLineNo = ws.Range("E1").Resize(RowSize:=LastRow).Value
' create output array
Dim ArrOut() As Variant 'define String column
ArrOut = ws.Range("D1").Resize(RowSize:=LastRow).Value
Dim CurrentConfigRow As Long
Dim iRow As Long
For iRow = 2 To LastRow
If ArrConfig(iRow, 1) = "C" Then
' is config line …
CurrentConfigRow = iRow ' remember line number for output
If iRow = LastRow Then
' base without options (in last row)
ArrOut(CurrentConfigRow, 1) = ArrPartNo(CurrentConfigRow, 1) ' write base part number to output (without dash)
ElseIf Not ArrSalesNo(CurrentConfigRow + 1, 1) = ArrSalesNo(CurrentConfigRow, 1) Or _
Not ArrLineNo(CurrentConfigRow + 1, 1) = ArrLineNo(CurrentConfigRow, 1) Or _
Not ArrConfig(CurrentConfigRow + 1, 1) = "X" Then
' base without options
ArrOut(CurrentConfigRow, 1) = ArrPartNo(CurrentConfigRow, 1) ' write base part number to output (without dash)
Else
' base with options
ArrOut(CurrentConfigRow, 1) = ArrPartNo(CurrentConfigRow, 1) & "-" ' write base part number to output (including dash)
End If
Else
' check if it is an option line of the remebered config line
If ArrSalesNo(iRow, 1) = ArrSalesNo(CurrentConfigRow, 1) And _
ArrLineNo(iRow, 1) = ArrLineNo(CurrentConfigRow, 1) And _
ArrConfig(iRow, 1) = "X" Then
' is option line (so append to output)
ArrOut(CurrentConfigRow, 1) = ArrOut(CurrentConfigRow, 1) & Mid$(ArrPartNo(iRow, 1), Len(ArrPartNo(CurrentConfigRow, 1)) + 2)
End If
End If
Next iRow
' write ouput to cells
ws.Range("D1").Resize(RowSize:=LastRow).Value = ArrOut
End Sub
输出看起来像