为什么我的offset()不能变量?

时间:2017-12-10 00:44:37

标签: excel vba

我尝试将每个工作表中的列排成一个摘要表。每张纸中的列数可以变化,每个列必须相互排列。我尝试使用以下代码:

  Sub Create_Summary()
  Dim sh As Worksheet, sumSht As Worksheet
  Dim i As Long
  Dim colCount As Long
  Dim rowCount As Long

  Sheets("Summary").Cells.ClearContents

  Set sumSht = Sheets("Summary")
  sumSht.Move after:=Worksheets(Worksheets.Count)

  For i = 1 To Worksheets.Count - 1

     colCount = sumSht.Columns.Count
     rowCount = Worksheets(i).Rows.Count

     Worksheets(i).Range("A:VV").Copy Destination:=sumSht.Cells(1, 
     colCount).End(xlToLeft).Offset(, 1)

  Next i
  sumSht.Columns(2).Delete

  End Sub

由于.Offset(,1)我不能正常工作,我猜...我不明白为什么我不允许使用.Offset(,colCount)因为那时我觉得它看起来不错。出于某种原因,如果我使用.Offset(,i)(没有任何意义),它就可以运行了。两者都是Long变量,所以有什么区别,我该如何解决这个问题呢? 提前谢谢......

1 个答案:

答案 0 :(得分:0)

为了实现这一目标,请考虑:

  • 获取您要为每张工作表移动的详细信息范围,并将其存储在detailRowCountdetailColCount
  • 通过增加每Summary次粘贴的列数值来跟踪detailColCount工作表中已使用的列。

示例代码:

Option Explicit

Sub Create_Summary()

    Dim sh As Worksheet, sumSht As Worksheet
    Dim i As Long
    Dim detailColCount As Long
    Dim detailRowCount As Long
    Dim summaryColCount As Long

    Sheets("Summary").Cells.ClearContents

    Set sumSht = Sheets("Summary")
    sumSht.Move after:=Worksheets(Worksheets.Count)

    summaryColCount = 1
    For i = 1 To Worksheets.Count - 1
        Set sh = Worksheets(i)
        detailColCount = sh.Cells(1, 1).End(xlToRight).Column
        detailRowCount = sh.Cells(1, 1).End(xlDown).Row

        sh.Range(sh.Cells(1, 1), sh.Cells(detailRowCount, detailColCount)).Copy _
            Destination:=sumSht.Cells(1, summaryColCount)

        summaryColCount = summaryColCount + detailColCount

    Next i

    'sumSht.Columns(2).Delete <-- ?

End Sub