如何将该范围更改为更具动态性?

时间:2018-12-26 15:17:22

标签: vba excel-vba

在执行数组宏之前,我有一个定义的范围,但是我必须颠倒定义它的方式。它以前是固定数量的列,但现在已转置,并且固定数量的行。

如何更改它以表示62 rows和列B to columns.count

With ThisWorkbook.Sheets("Profiles")
Data = .Range("bj1", .Range("B" & Rows.Count).End(xlUp))
End With

或者甚至更进一步,我该如何做columns&rows.count?

整个脚本:

Option Explicit

Sub Main()
  Dim wb As Workbook
  Dim Data, Last, JobFamily
  Dim i As Long, j As Long, k As Long, a As Long
  Dim Dest As Range

  'Refer to the template
  Set wb = Workbooks("Book2.xlsx")
  'Refer to the destination cell
  Set Dest = wb.Sheets("Sheet11").Range("B1")
  'Read in all data
  With ThisWorkbook.Sheets("Profiles")
    Data = .Range("B1", .Cells(.Cells(.Rows.Count, 2).End(xlUp).Row, .Columns.Count).End(xlToLeft))
End With
  wb.Activate
  Application.ScreenUpdating = False

  'Process the data
  For i = 1 To UBound(Data)
    'Manager changes?
    If Data(1, i) <> Last Then
      'Skip the first
      If i > 1 Then
        'Scroll into the view
        Dest.Select
        'Save a copy
        wb.SaveCopyAs ThisWorkbook.Path & Application.PathSeparator & _
          ValidFileName(Last & ".xlsx")
      End If
      'Clear the employees
      Dest.Resize(, Columns.Count - Dest.Column).EntireColumn.ClearContents
      'Remember this manager
      Last = Data(1, i)
      'Start the next round
      j = 0
    End If
    'Write the employee data into the template
    a = 0
    For k = 1 To UBound(Data, 2)
      Dest.Offset(a, j) = Data(k, i)
      a = a + 1
    Next
    'Next column
    j = j + 1
  Next
End Sub

在此行出现subscript out of range错误:

Dest.Offset(a, j) = Data(k, i)

1 个答案:

答案 0 :(得分:0)

基于评论中的进一步澄清:

With ThisWorkbook.Sheets("Profiles")
    Data = .Range("B1", .Cells(62, .Columns.Count).End(xlToLeft))
End With

而如果您想使B列的最后一行保持动态(并始终抓住后者的最后一列):

With ThisWorkbook.Sheets("Profiles")
    Data = .Range("B1", .Cells(.Cells(.Rows.Count, 2).End(xlUp).Row, .Columns.Count).End(xlToLeft))
End With