嵌套循环excelvba-Shiftleft

嵌套循环excelvba-Shiftleft,vba,excel,Vba,Excel,我正在尝试创建一个新程序。我导入了一个csv文件,数据需要清理。第一行的标题正确,但与应分配给列标签的内容不匹配 例如: 正确的行应为: A B C D bxxxxxxx1 1994 7890 main 不正确的行,例如: bxxxxxxx1 bxxxxxxx2 1994 1995 7890 7891 main main bxxxxxxx1 bxxxxxxx2 bxxxxxxx3 bxxxxxxx4 1994 1995 1996 1997 7890 7

我正在尝试创建一个新程序。我导入了一个csv文件,数据需要清理。第一行的标题正确,但与应分配给列标签的内容不匹配

例如: 正确的行应为:

A         B     C      D
bxxxxxxx1 1994  7890   main
不正确的行,例如:

bxxxxxxx1 bxxxxxxx2 1994 1995 7890 7891  main main
bxxxxxxx1 bxxxxxxx2 bxxxxxxx3 bxxxxxxx4 1994 1995 1996 1997 7890 7891 7890 7891 main main main main
bxxxxxxx1 bxxxxxxx2 bxxxxxxx3 1994 1995 1996 7890 7891 7892 main main main
bxxxxxxx1....bxxxxxxxn 1994....yearn...7890...789n...main1....mainn
因此,不正确的行多次提供b值,然后是它们各自的值,这将用多个b值偏移所有行。因此,我想删除BXXXXXXXX219995、7891和第二个main,保留其余部分(将所有内容向左移动以与列标题对齐)

我目前拥有的代码:

Sub bibcheck()
    Dim Cel As Range
    Dim n As Integer
    bibfound = 0

    For i = 3 To 9
        n = 0
        For j = 2 To 9
            Set Cel = Cells(i, j)

            If Cel Like "b*#" Or Cel Like "b*?" Then
                n = n + 1
                '  MsgBox n  :'to verify record is found
                Cel = ""    'Clear the bib record found


            'Insert new code
            'Use each n created per row to create a new loop for shifting to the  left
            'skip a value, then use n again to delete that many cells to the right, continuously shifting blanks to the left.

            Else  
            End If 
        Next
    Next
End Sub

这将满足您的要求:

Sub bibcheck()
Dim ws As Worksheet
Dim lastrow As Long
Dim lastclm As Long
Dim i As Long
Dim j As Long
Dim oArr(1 To 4) As Variant
Dim t As Integer

Set ws = ThisWorkbook.ActiveSheet

With ws
    lastrow = .Cells(.Rows.Count, 1).End(xlUp).Row
    For i = 3 To lastrow
        lastclm = .Cells(i, .Columns.Count).End(xlToLeft).Column
        j = Application.WorksheetFunction.CountIf(.Range(.Cells(i, 1), .Cells(i, lastclm)), "b*")
        t = 1
        For j = 1 To lastclm Step j
            oArr(t) = .Cells(i, j).Value
            t = t + 1
        Next j
        .Range(.Cells(i, 1), .Cells(i, lastclm)).ClearContents
        .Range(.Cells(i, 1), .Cells(i, 4)).Value = oArr
    Next i
End With

End Sub
之前:

之后:


应该有多少列数据?在您的示例中,您有4个,但代码看起来是9个。通常情况下,9列是正确的吗?我在I=3到0和j=2到9中使用的示例是任意值,用于测试每一行和每一列,以确保当我使用MsgBox时,它打印出我期望的值(我不擅长编程)。实际上,最多有7列包含bxxxxxx,以及大约10000行数据。看起来第一行是重复的,并且与第二行混合在一起。我对您的示例感到困惑,直到看到您将数据扩展到包含第三组数据。我想如果是这样的话,你应该多出一行。在任何情况下,它都可以在OP的数据集上工作+1可以将上面的内容修改为不被4除,因为如果你没有可以被4除的东西怎么办?是否有一种简单的方法来修改循环以查找“b”值和ClearContent,以及根据找到的b值的数量进行移位,并删除其各自的数据单元?如果每个“b”值并不总是有四个数据点,那么您如何知道哪些数据点属于哪个“b”?根据您的示例,所有“b”都有4个数据点。例如,如果第二个数据点有3个“B”,但只有2年,Excel将永远无法知道哪些点要删除,哪些点要保留。必须始终存在一个模式,否则它将不起作用。数据列实际上从a:AE扩展而来。我提供了该模式的一个片段,以找出删除这些值的方法。因此正确的值应该是A:AE,而例如,我有一行的4b值开始扩展到BR。