嵌套循环Excel VBA – Shiftleft

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

例如:正确的行应该是:

ABCD 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值偏移了所有的行。 所以我想删除bxxxxxxx2,1995,7891和第二主要的,保留其余的(把所有东西左移与列标题alignment)

我目前的代码是:

 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 

之前:

在这里输入图像说明

后:

在这里输入图像说明