我决定从头开始这个问题,以澄清问题和目标。
关于我的数据需要注意的事情
示例数据在同一个工作表中并排格式化:

单独工作表中的示例数据(sheet1 =电池,sheet2 =充电器):

无论使用哪种方法,模型字段都可以放置在A列中的任何位置--当比较这两组数据时,模型字段将不在相邻的单元格中(如图所示)
我正在努力实现的
期望输出

值得一提的是,这是我将要处理的数据的一个非常小的示例,完整的数据集超过60k行,并且不断增长,因此解决方案需要是高效的。
我正在使用excel 2007。
我是一个完全的新手与VBA,我买了一些插件,试图实现我的目标,我花了两天的研究和尝试各种方法来做,但都没有任何效果。
我以为我已经接近桑托什的回答了:
https://stackoverflow.com/a/19780188/1018153
这就是我之前问题的基础,但是除了在模型之间生成重复和匹配的数据之外,我无法将我的数据格式化为它的完整形式,以便脚本对我起作用,所以我最初的问题是无关紧要的。
发布于 2014-01-28 16:48:48
下面的语句应该仍然有效,但是我编写了代码来解释它是如何工作的。
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 SubPreviousAnswer
查看您所指出的问题中的代码,您将需要存储当前模型,并且只在模型匹配时添加可能性。当数据被写入时,这将导致大量的#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
Loophttps://stackoverflow.com/questions/21408416
复制相似问题