VBA代码正在运行但没有效果

时间:2017-02-14 15:39:21

标签: excel vba excel-vba

以下代码用于预期目的:将一些行从一个工作表复制到另一个工作表。但是,当我使用rangeToDelete添加部件时,这意味着在每次新运行代码之前清除我正在复制的空间。我不确定发生了什么,但是当我使用MsgBox来验证代码的某些部分时,它看起来就像是循环不起作用。但是,如果没有错误,我不知道为什么。

Option Explicit

Sub findCells()
  Dim topCell As String
  Dim leftCell As String
  Dim refCell As Range
  Dim sht As Worksheet
  Dim lastRow As Long
  Dim i As Long
  Dim cellVal As String
  Dim altCounter As Long
  Dim crange As Range
  Dim rangeToDelete As Range

  Set rangeToDelete = Worksheets("Summary").Cells(31, "A").CurrentRegion
  rangeToDelete.Value = ""

  Set refCell = ActiveCell
  topCell = refCell.End(xlUp).Value
  leftCell = refCell.End(xlToLeft).Value

  Set sht = Worksheets(topCell)
  lastRow = sht.Cells(sht.Rows.Count, "A").End(xlUp).Row
  With sht
    .Range("A1:G1").Copy Worksheets("Summary").Range("A31:G31")
    altCounter = 31
    For i = 1 To lastRow
      cellVal = Cells(i, 5).Value
      If leftCell = cellVal Then
        altCounter = altCounter + 1
        Set crange = .Range("A" & i & ":" & "G" & i)
        crange.Copy Worksheets("Summary").Range("A" & altCounter & ":" & "G" & altCounter)
      End If
    Next i
  End With

End Sub

1 个答案:

答案 0 :(得分:0)

range.cells在代码中使用数字而非文本使用1作为列A.并且还用于清除建议的内容方法。