2017-09-26 72 views
1

我有100K的Excel文件,其中有许多员工信息,我想将所有存在的数据移至此员工的第一行,下面的图片会比我的文字更响亮,可以使用VBA代码做这个?或有Excel中的一个把戏,我不知道的将所有行移至第一个行

I want the data to the left to be same as the right

+1

是的,VBA代码可以做到这一点。我不认为你可以用Power Query来做到这一点。并且手动方法对您的大型数据库来说过于繁琐 –

回答

2

试试下面的代码。

Sub Demo() 
    Dim ws As Worksheet 
    Dim cel As Range, rng As Range 
    Dim lastRow As Long, lastCol As Long, i As Long 
    Dim fOccur As Long, lOccur As Long, colIndex As Long 
    Dim dict As Object, c1 
    Application.ScreenUpdating = False 

    Set ws = ThisWorkbook.Sheets("Sheet1") 'change Sheet1 to your data range 
    Set dict = CreateObject("Scripting.Dictionary") 

    With ws 
     lastRow = .Cells(.Rows.Count, "A").End(xlUp).Row 'last row with data in Column A 
     lastCol = .Cells.Find(What:="*", _ 
         After:=.Range("A1"), _ 
         Lookat:=xlPart, _ 
         LookIn:=xlFormulas, _ 
         SearchOrder:=xlByColumns, _ 
         SearchDirection:=xlPrevious, _ 
         MatchCase:=False).Column  'last column with data in Sheet1 

     Set rng = .Range("A1:A" & lastRow)    'set range in Column A 
     c1 = .Range("A2:A" & lastRow) 
     For i = 1 To UBound(c1, 1)      'using dictionary to get uniques values from Column A 
      dict(c1(i, 1)) = 1 
     Next i 

     colIndex = 16  'colIndex+1 is column number where data will be displayed from 
     For Each k In dict.keys  'loopthrough all unique values in Column A 
      fOccur = Application.WorksheetFunction.Match(k, rng, 0) 'get row no. of first occurrence 
      lOccur = Application.WorksheetFunction.CountIf(rng, k) 'get row no. of last occurrence 
      lOccur = lOccur + fOccur - 1 

      'copy range from left to right 
      .Range(.Cells(fOccur, 1 + colIndex), .Cells(lOccur, lastCol + colIndex)).Value = .Range(.Cells(fOccur, 1), .Cells(lOccur, lastCol)).Value 
      'delete blanks in range at right 
      .Range(.Cells(fOccur, 1 + colIndex), .Cells(lOccur, lastCol + colIndex)).SpecialCells(xlCellTypeBlanks).Delete Shift:=xlUp 'delte blank rows 
     Next k 
    End With 
    Application.ScreenUpdating = True 
End Sub 

enter image description here

+0

谢谢,您是我的一天:) –

+0

@Mrig尼斯。 +1 :) – sktneer

+0

@MohammadAwniAli - 不客气! – Mrig

0

尝试以下。您可以修改以下代码以匹配您要移动范围的位置:

Dim oW As Worksheet: Set oW = ThisWorkbook.Worksheets("Sheet8") 

With oW.UsedRange 
    .Cut .Offset(0, .Columns.Count + 2) 
End With 
相关问题