为什么我会为这行编码获得超出范围UBound的下标?

时间:2016-07-21 07:08:56

标签: vba

'the array is from 0 till the number of sheets

Sub FilterToSheets()
  Dim SourceSheet As Worksheet
  Dim TargetSheet As Worksheet
  Dim SheetNames As Variant
  Dim i As Long
  Dim LR As Long

  Set SourceSheet = Sheets("Yield - Weekly.rdl") 'the name of sheet that contains the data
  SheetNames = Array("MV1", "MV2", "DA1", "F1", "SF1") 'the name categories in the table to be separate according to this sheets

  Const FilterColumn = 7 'the number of column

  'from the source sheet
  With SourceSheet
    LR = .Range("A" & .Rows.Count).End(xlUp).Row
    'array loops from 0

    For i = 0 To UBound(SheetNames)
      Set TargetSheet = Worksheets(SheetNames(i))
      TargetSheet.Cells.ClearContents
      'starts from the range a5 till R
      With .Range("A5:R" & LR)
        .AutoFilter Field:=FilterColumn, Criteria1:=SheetNames(i)
        .Offset(0, 0).Copy TargetSheet.Range("A5")
      End With
      'continue to next loop
    Next i
  End With
End Sub

0 个答案:

没有答案