2016-10-31 61 views
0

我做了這個宏(它工作!),但我想擴大它。 「數據」表中的一些數據是不相關的,我不想在「數據處理」表中自動填充這些行。VBA拉斯特羅不包括某些值

我想更改LastRow定義。我的數據資料中的G列包含很多日期和時間(例如2016-09-26 09:42:56.290),並且與最後一個日期(2016-09-26)相關的數據與我的分析混淆了很多的空值,因爲目前還沒有數據)。由於我必須定期更新這本工作手冊,所以我不能說排除2016-09-26。宏必須查看數據表底部的日期,並將選擇向上移動,以便這些日期不包含在選擇中。

那麼我該怎麼做呢?

Sub Kviklevering_Drag_Down() 

On Error GoTo errHandler 
Application.ScreenUpdating = False 

    With ActiveWorkbook 
    Lastrow = ActiveWorkbook.Sheets("Data").UsedRange.Rows.Count 

    Sheets("Databehandling").Activate 

    Range("A2:V2").Select 

    Selection.AutoFill Destination:=Range("A2:V" & Lastrow), Type:=xlFillDefault 
    End With 

Sheets("Databehandling").Visible = False 
Sheets("Data").Activate 

Application.ScreenUpdating = True 

errHandler: 
Application.ScreenUpdating = True 

End Sub 
+0

嘗試增加-1到你設置LASTROW:LASTROW = ActiveWorkbook.Sheets(「數據」)UsedRange.Rows.Count -1 – Thom

+0

如果每個日期只出現一次,然後用-1是@Thomas說,否則使用COUNTIF來獲取最後一次出現的頻率並從最後一行中刪除 - 提供日期是按順序排列的。 –

+0

我不會使用USEDRANGE - 這可能會導致不正確的結果。使用類似'.Cells(.Rows.Count,1).End(xlUp).Row'(對於列A)。 –

回答

0

我已更新您的代碼。取消查看ActiveBook,激活工作表並將錯誤處理程序移至主程序之外(在Exit Sub之後,但在End Sub之前)。

Sub Kviklevering_Drag_Down() 

    Dim CountOfMaxDate As Long 
    Dim rLastCell As Range 
    Dim rCountRange As Range 
    Dim dMaxDate As Double 


    'Are you sure it's always the ActiveWorkbook? 
    'May be better to use ThisWorkbook which is always the file with this code in, 
    'or a specific named workbook. 
    'With ActiveWorkbook 
    On Error GoTo ErrorHandler 

    With ThisWorkbook 

     With Worksheets("Data") 
      'Find last cell in column G (column 7). 
      Set rLastCell = .Cells(.Rows.Count, 7).End(xlUp) 
      If rLastCell.Row = 1 Then 
       Err.Raise vbObjectError + 1000, , "Last Cell is row 1" 
      End If 
      Set rCountRange = .Range(.Cells(1, 7), rLastCell) 
      'Get the value of the last date. 
      dMaxDate = Int(rLastCell) 

      'Count the last date. 
      CountOfMaxDate = WorksheetFunction.CountIfs(rCountRange, ">=" & dMaxDate, rCountRange, "<" & dMaxDate + 1) 
     End With 

     'No need to active this sheet - can leave it hidden if you want. 
     With Worksheets("Databehandling") 
      .Range("A2:V2").AutoFill Destination:=.Range("A2:V" & rLastCell.Row - CountOfMaxDate), Type:=xlFillDefault 
     End With 

    End With 

FastExit: 
    'Tidy up before exiting procedure. 

Exit Sub 

    On Error GoTo 0 
    Exit Sub 

ErrorHandler: 

    Select Case Err.Number 
     Case -2147220504 'Last Cell is row 1 
      'Handle error. 

      'Possible things to do after error handled: 
      'Resume Next 
      'Resume 
      'Resume FastExit 
     Case Else 
      MsgBox "Error " & Err.Number & " (" & Err.Description & ") in procedure Kviklevering_Drag_Down." 
    End Select 

End Sub