【发布时间】:2014-10-10 15:00:12
【问题描述】:
如果能帮助我找到解决问题的正确方法,我将不胜感激。
我需要从不同的工作表中处理数据。
在表格 1 中,我有这个数据列表。
Key Reference COL B COL C COL D
ID123 YZA ... ...
ID123 BBA ... ...
ID123 XCP ... ...
ID123 ABC
ID123 empty cell
ID123 …
ID124 empty cell
ID124 XCP
… …
在 sheet2 中,我将只有唯一引用列表
ID123
ID124
ID125
...
通过唯一引用,我需要使用以下条件对 B 列中的数据进行排序:
- 空单元格
- 字符串“XCP”
- 其余所有(从 ABC 到 YZA)
然后,通过唯一引用计算行数 在 sheet2 中插入此行数 并粘贴已排序的数据。
我认为最简单的方法是对我的每个条件使用带有 If 语句的循环,而不是排序选项。
预期结果是:所以它似乎与表 1 相同,但 col b 尊重我的排序条件
Key Reference COL B COL C COL D
ID123 empty cell ... ...
ID123 XCP ... ...
ID123 ABC
ID123 YZA
ID123 …
ID124 empty cell
ID124 XCP
请看下面我尝试创建的代码
Sub mapbreak5()
Dim lr As Long, r As Long
lr = Sheets("Sheet1").Cells(Rows.Count, "A").End(xlUp).Row
Dim rngKey As Range
For r = 2 To lr
If Sheets("Sheet1").Range("B" & r).Value = "" Then
'...
End If
Next r
'Or =>
Do
If Range("B2") Is Empty Then
Copy.EntireRow
'find the respective key refence in the breaks sheet
ThisWorkbook.Worksheets("breaks").Cells.Find(rngKey.Value, searchorder:=xlByRows, searchdirection:=xlPrevious).Row
'check if the IDxx field is already populated
If Range("F2") Is Empty Then
Range("E2").Paste.Selection
Else: ActiveCell.Offset (1)
Rows.Select
Selection.Insert Shift:=xlDown
End If
Else: ActiveCell.Offset (1)
End If
Loop Until IsEmpty(ActiveCell.Offset(0, -1))
Do
If Range("B2") = "XCP" Then
Copy.EntireRow
'find the respective key refence in the breaks sheet
ThisWorkbook.Worksheets("breaks").Cells.Find(rngKey.Value, searchorder:=xlByRows, searchdirection:=xlPrevious).Row
'check if the IDxx field is already populated
If Range("F2") Is Empty Then
Range("E2").Paste.Selection
Else: ActiveCell.Offset (1)
Rows.Select
Selection.Insert Shift:=xlDown
End If
Else: ActiveCell.Offset (1)
End If
Loop Until IsEmpty(ActiveCell.Offset(0, -1))
Do
If Range("B2") Is Not Empty Or "XCP" Then
Copy.EntireRow
'find the respective key refence in the breaks sheet
ThisWorkbook.Worksheets("breaks").Cells.Find(rngKey.Value, searchorder:=xlByRows, searchdirection:=xlPrevious).Row
'check if the IDxx field is already populated
If Range("F2") Is Empty Then
Range("E2").Paste.Selection
Else: ActiveCell.Offset (1)
Rows.Select
Selection.Insert Shift:=xlDown
End If
Else: ActiveCell.Offset (1)
End If
Loop Until IsEmpty(ActiveCell.Offset(0, -1))
End Sub
【问题讨论】:
-
你试过什么?结果如何?这不是代码编写服务,但我们很乐意帮助您调试代码。有关如何提出好问题的信息,请参阅 stackoverflow.com/help。
-
谢谢罗恩,我会看到如何提出一个好问题的帮助。我还用我尝试过的代码更新了我最初的问题。我将继续朝这个方向尝试,除非我被告知这不是最好的方法。
-
在交互式执行任务时录制宏,然后检查宏。
-
@LK.3 如果您能根据输入显示您对结果的期望,那将会很有帮助。
-
@RonRosenfeld 我通过编辑我的初始问题来回答您的问题。谢谢