VBA - 意外的行插入

时间:2016-11-30 17:47:18

标签: excel vba excel-vba

目的

从多个工作表中复制一组行并插入CONSOLIDATED工作表。

APPROACH

  1. 转到CONSOLIDATED工作表并删除已有的信息
  2. 使用IF语句查找我们打算从
  3. 中提取数据的相关工作表
  4. 复制每个工作表上的相关列和行(例如A6:G(lastrow))
  5. 将复制的数据附加到CONSOLIDATED工作表 !!!错误
  6. (丑陋)代码

    Sub consolidateConvert()
    Dim ws As Worksheet
    
    'Set CONSOLIDATED as the active worksheet
    Application.ScreenUpdating = False
    Sheets("CONSOLIDATED").Activate
    
    
    'Clear previous content from active sheet
    ActiveSheet.Range("A1:G10000").ClearContents
    
    'Iterate through workbooks, except for CONSOLIDATED, TITLE, and PIVOT worksheets
    For Each ws In Worksheets
      If ws.Name <> "CONSOLIDATED" And ws.Name <> "PIVOT" And ws.Name <> "TITLE" _
         And ws.Name <> "APPENDIX - CURRENCY CONVERTER" And ws.Name <> "MACRO" Then
    
    'Find last row of current worksheet
        Dim lastRow As Long
        lastRow = ws.Cells(ws.Rows.Count, "E").End(xlUp).Row
    
    'Copy current worksheet cells and insert into CONSOLIDATED worksheet
        ws.Range("A6:G" & lastRow).Copy
        ActiveSheet.Range("A2").End(xlUp).Insert shift:=xlDown
      End If
    Next ws
    
    Call currencyConvert
    Call addHeaders
    

    currencyConvert是与此特定问题无关的函数。但是,我在下面添加了addHeaders函数:

    Sub addHeaders()
    Dim ws As Worksheet
    Dim headers() As Variant
    
    'Define worksheet and desired headers
    Set ws = ThisWorkbook.Sheets("CONSOLIDATED")
    headers() = Array("Fiscal Year", "Month", "Fiscal Month", "Month Year", "Unit", "Project", "Local Expense", "Base Expense")
    
    'Insert row for header placement
    Rows(1).Insert shift:=xlShiftDown
    
    'Insert headers
    With ws
      For i = LBound(headers()) To UBound(headers())
        .Cells(1, 1 + i).Value = headers(i)
      Next i
    End With
    End Sub
    

    输出

    下面是意外输出的屏幕截图。第2-7行是意外的,包括一些随机文本字符串,这些字符串在工作簿中的任何其他位置都不存在。字符串可能是VBA中的一些奇怪的继承问题,但不太确定(因此下面的问题)。

    error with weird text strings

    问题

    1. 如前所述,第2-7行是无意中添加的,并附有一些奇怪的字符串。有没有人知道为什么要添加~6行(当只添加1行时 - 请参阅addHeaders())?另外,非预期字符串的起源是什么(“CatalogNickname”,“EnvironmentKey”等)?

1 个答案:

答案 0 :(得分:1)

您的问题源于使用Activate / ActiveSheet

你必须放弃这种编码习惯,这可能会巧妙地误导你,并使用完全合格的范围参考来确保你对所需的工作簿/工作表范围采取行动

下面是使用完全限定范围引用和&#34; Value to Value&#34;重构代码。 range复制代替Copy / Insert来大幅提升速度:

Option Explicit

Sub consolidateConvert()
    Dim ws As Worksheet
    Dim lastRow As Long

    With Worksheets("CONSOLIDATED") '<--| reference "CONSOLIDATED" worksheet
        .UsedRange.ClearContents '<--| clear its content

        'Iterate through workbooks
        For Each ws In Worksheets
            Select Case ws.Name
                Case "CONSOLIDATED", "PIVOT", "TITLE", "APPENDIX - CURRENCY CONVERTER", "MACRO" ' <--| discard "CONSOLIDATED", "TITLE", "PIVOT", "APPENDIX - CURRENCY CONVERTER" and "MACRO" worksheets
                    ' do nothing
                Case Else
                    'Find last row of current worksheet
                    lastRow = ws.Cells(ws.Rows.Count, "E").End(xlUp).row
                    'Copy current worksheet cells and insert into CONSOLIDATED worksheet
                    .Cells(.Rows.Count, 1).End(xlUp).Offset(1).Resize(lastRow - 5, 7).Value = ws.Range("A6:G" & lastRow).Value '<--| just copy values and speed thing up!
            End Select
        Next ws
        addHeaders .Name '<--| call AddHeaders passing reference worksheet name (i.e. "CONSOLIDATED")
    End With

    currencyConvert '<--| if it acts on "CONSOLIDATED" sheet, you may want to "treat" it as 'addHeaders': take it into 'End With' and pass it '.Name' as a parameter 

End Sub

Sub addHeaders(shtName As String)
    Dim headers As Variant

    headers = Array("Fiscal Year", "Month", "Fiscal Month", "Month Year", "Unit", "Project", "Local Expense", "Base Expense") '<--| Define desired headers
    ThisWorkbook.Worksheets(shtName).Range("A1").Resize(, UBound(headers) - LBound(headers) + 1).Value = headers '<--| write headers from cell A1 rightwards
End Sub