我决定从头开始这个问题,以澄清问题和目标。
有关我的数据的注意事项
在同一工作表中并排格式化的示例数据:
单独工作表中的示例数据(sheet1 = battery,sheet2 = chargers):
无论使用哪种方法,模型字段都可以放在A列的任何位置 - 比较两组数据时,模型字段不会位于相邻的单元格中(如图所示)
我想要实现的目标
所需输出
值得一提的是,这是我将要处理的数据的一个非常小的样本,完整数据集超过6万行并且不断增长,因此解决方案需要高效。
我正在使用excel 2007。
我是VBA的完全菜鸟,我已经购买了一些插件来尝试实现我的目标,我花了2天的时间研究并尝试了各种方法来做到这一点,但都无济于事。
我以为我已经接近了Santosh的回答:
https://stackoverflow.com/a/19780188/1018153
这是我基于上一个问题的基础,但是除了在模型之间产生重复和匹配数据之外,我实际上无法将数据格式化为完整形式,因为该脚本无论如何都适合我,所以我的原始问题无关紧要
答案 0 :(得分:2)
下面的陈述应该仍然有用,但是我编写了代码来试图解释它是如何工作的
Option Explicit 'This ensures typos in variable names are flagged
Sub MakeList()
Dim BatteryList As Range
Dim ChargerList As Range
Dim CurrentModel As String
Dim i As Long
Dim j As Long
Dim k As Long
Dim resultrange As String
'look at the lists - note I am not looking at the type - I'm going to assume
'that we can set the address correctly
'use End(xLdown) to find the last cell - that way we don't need to
'remember to change it when the number of items changes
Set BatteryList = Worksheets("Sheet1").Range("A2", Range("sheet1!B1").End(xlDown))
Set ChargerList = Worksheets("Sheet2").Range("A2", Range("Sheet2!B1").End(xlDown))
'note the use of the Sheet2! and sheet1! in the .End(xlDown) - this is required
'even though we have the Worksheets(" to set the range
i = 2 ' result row
For j = 1 To BatteryList.Rows.Count ' look at each battery row
CurrentModel = BatteryList(j, 1)
For k = 1 To ChargerList.Rows.Count 'then look at each charger row
If ChargerList(k, 1) = CurrentModel Then
'and only write a row if the battery and charger models match
Worksheets("Sheet3").Cells(i, 1) = CurrentModel
Worksheets("Sheet3").Cells(i, 2) = BatteryList(j, 2)
Worksheets("Sheet3").Cells(i, 3) = ChargerList(k, 2)
i = i + 1
End If
Next k
Next j
End Sub
PreviousAnswer
查看您指出的问题中的代码,您需要存储当前模型,并且仅在模型匹配时添加可能性。当数据被写出时,这将导致大量的 #N / A!,但这应该是一个小修复。
在这一行:
Do While j <= UBound(c1)
我会插入代码来保存当前模型
Dim OnlyThisModel as string
Do While j <= UBound(c1)
OnlyThisModel=c1(j,1)
并在此区域
Do While m <= UBound(c4)
out(n, 1) = c1(j, 1)
out(n, 2) = c2(k, 1)
out(n, 3) = c3(l, 1)
out(n, 4) = c4(m, 1)
n = n + 1
m = m + 1
Loop
检查模型是否正确,如果不是,则不要写:
Do While m <= UBound(c4)
if c1(j,1)=OnlyThisModel then
'Only write out data if model matches
out(n, 1) = c1(j, 1)
out(n, 2) = c2(k, 1)
out(n, 3) = c3(l, 1)
out(n, 4) = c4(m, 1)
n = n + 1
end if
'go to next record, regardless of if a combination was written
m = m + 1
Loop