VBA - 在excel中排列数据值

时间:2013-12-17 11:02:54

标签: excel-vba vba excel

道歉,但我是VBA的新手。我已经使用该网站解决了我有匹配2列数据的问题;

IP26 5BN    IP26 5BN
IP26 5BN    IP26 5DB
IP26 5DB    IP26 5DB
IP26 5EL    IP26 5EL
IP26 5ET    IP26 5EL
IP26 5ET    IP26 5ET
IP26 5HN    IP26 5ET
IP26 5HR    IP26 5HN
IP26 5HR    IP26 5HR
IP26 5JA    IP26 5JA
IP26 5JA    IP26 5JA
IP26 5NJ    IP26 5NJ
IP27 0DJ    IP27 0DJ
IP27 0DZ    IP27 0DZ
IP27 0ER    IP27 0ER
IP27 0JN    IP27 0JN

项目可以在A列和A列中。 B多次,我想排列A中的任何项目与B中的匹配元素,反之亦然,当有一个额外的“相同”值时,在A和B中插入一个空行。

我必须;

Sub Expand()
Dim first_col As Range
Dim second_col As Range
Dim row As Integer

Set first_col = Range("A1:A17")
Set second_col = Range("B1:B17")

For row = 1 To second_col.Rows.Count
    If (first_col.Cells(row, 1).Value = second_col.Cells(row, 1).Value Or second_col.Cells(row, 1).Value = first_col.Cells(row, 1).Value) Then
    End If

        If first_col.Cells(row, 1).Value <> second_col.Cells(row, 1).Value Then
        second_col.Cells(row, 1).Insert shift:=xlDown
        ElseIf first_col.Cells(row, 1).Value = second_col.Cells(row, 1).Offset(1, 0).Value Then
        '// code to insert the row
        first_col.Cells(row, 1).Insert shift:=xlDown


    End If
Next row
End Sub

但是发生的事情是第1次,如果并不总是在我认为它应该返回“真实”的时候,那么阵容就会向下移动,或者当有重复时它们会对齐到最后一行。

有什么建议吗?

2 个答案:

答案 0 :(得分:0)

您的第一个If阻止为空。

你的意思是这样做吗?

For Row = 1 To second_col.Rows.Count
    If (first_col.Cells(Row, 1).Value = second_col.Cells(Row, 1).Value Or second_col.Cells(Row, 1).Value = first_col.Cells(Row, 1).Value) Then
    'End If <-- Remove this

        If first_col.Cells(Row, 1).Value <> second_col.Cells(Row, 1).Value Then
        second_col.Cells(Row, 1).Insert shift:=xlDown
        ElseIf first_col.Cells(Row, 1).Value = second_col.Cells(Row, 1).Offset(1, 0).Value Then
        '// code to insert the row
        first_col.Cells(Row, 1).Insert shift:=xlDown
        End If '<-- Add this

    End If
Next Row

答案 1 :(得分:0)

我不完全理解你的问题。但是我假设您要在活动单元格下面插入新行。 我想这可能会对你有帮助。

<强> ActiveCell.Offset(1).EntireRow.Insert

相关问题