【问题标题】:VBA: Trying to consolidate all worksheets into one new worksheet in single workbookVBA:尝试将所有工作表合并到单个工作簿中的一个新工作表中
【发布时间】:2016-10-11 23:34:47
【问题描述】:

我正在尝试一次复制所有工作表,然后粘贴到新工作表中。这些文件来自多个第三方,因此工作表可能会有所不同。在尝试确定最后一行Lrow 和最后一列Lcol 时,我遇到了以下问题,因为出现错误Object doesn't support this property or method。我确实计划将此提交到我的工作中,因此感谢任何有关防错或一般宏提示的帮助。

Sub ws_copy()
Dim Lrow As Long
Dim Lcol As Long
Dim Pasterow As Long
Dim WSCount As Integer
Dim i As Integer

'On Error Resume Next
    'Application.DisplayAlerts = False
        i = Application.InputBox(prompt:="Enter the place order of first tab to be copied.", Title:="Worksheet Consolidation", Type:=1)


    If IsEmpty(i) = True Then
        Exit Sub
    Else

    If IsNumeric(i) = False Then
        MsgBox "Enter a numeric value."
    Else

    If IsNumeric(i) = True Then
         Worksheets.Add(before:=Sheets(1)).Name = "Upload"


            WSCount = Worksheets.Count

        For i = i + 1 To WSCount


        Lrow = Worksheets(i).Find("*", After:=Cells(1, 1), _
                    LookIn:=xlFormulas, _
                    Lookat:=xlPart, _
                    SearchOrder:=xlByRows, _
                    SearchDirection:=xlPrevious, _
                    MatchCase:=False).Row

        Lcol = Worksheets(i).Find("*", After:=Cells(1, 1), _
                    LookIn:=xlFormulas, _
                    Lookat:=xlPart, _
                    SearchOrder:=xlByColumns, _
                    SearchDirection:=xlPrevious, _
                    MatchCase:=False).Row


    Pasterow = Lrow + 1

    Workbook.Worksheets(i).Range(Cells(1, 1), Cells(Lrow, Lcol)).Copy
    Workbook.Worksheets("Upload").Cells(Pasterow, 1).Paste



        Next i

    Else
    Exit Sub

    End If
    End If
    End If

'On Error GoTo 0
'Application.DisplayAlerts = False

End Sub

【问题讨论】:

  • 由于收到的文件种类繁多,我不能假设任何一列都会包含最后一个单元格
  • 带有 Lrow 和 Lcol 的代码返回错误,指出对象不支持此属性或方法
  • 是的,我们的想法是在每次粘贴新 WS 时确定“上传”表中的最后一行,然后从该行向下移动一行,这样粘贴就可以在不弄乱数据的情况下进行。
  • 是的,成功了!现在有一个新问题。以下代码出现“Object required”错误 Workbook.Worksheets(i).Range(Cells(1, 1), Cells(Lrow, Lcol)).Copy
  • 限定行是什么意思?

标签: vba excel macros


【解决方案1】:

查找最后一行/列的常用方法是:

With Worksheets(i)

    Lrow = .Cells(.Rows.Count, 1).End(xlUp).Row
    Lcol = .Cells(1, .Columns.Count).End(xlToLeft).Column

End With

第

【讨论】:

  • 对,但由于收到的文件种类繁多,我不能假设任何一列或一行都有最后一条数据。
【解决方案2】:

基于以下评论:

由于收到的文件种类繁多,我不能假设任何一列或一行都有最后一条数据。

您应该考虑使用工作表 (MSDN) 的 UsedRange 属性。 UsedRange 随着更多数据输入到工作表中而扩展。

有些人会避免使用UsedRange,因为如果输入了一些数据,然后将其删除,那么UsedRange 将包含这些“空”单元格。 UsedRange 将在保存工作簿时自行更新。但是,就您而言,这听起来不像是一个相关问题。

一个例子是:

Sub Test()

    Dim wsSource As Worksheet
    Dim wsTarget As Worksheet
    Dim rngSource As Range
    Dim rngTarget As Range

    Set wsSource = ThisWorkbook.Worksheets("Sheet1")
    Set wsTarget = ThisWorkbook.Worksheets("Sheet2")
    Set rngSource = wsSource.UsedRange

    rngSource.Copy Destination:=wsTarget.Cells

End Sub

【讨论】:

  • 这很好。我很担心,因为有时这些工作表最初会根据我们接收信息的方式而出现在不同的工作簿中,因此必须将它们复制到一个工作簿中,因此有人可能会在复制数据之前不小心弄乱数据,但我想这只会增加“使用范围” '所以可能没有重大不利因素,对吧?感谢您的反馈!
【解决方案3】:

这是一种查找工作表中最后使用的行和最后使用的列的方法。它避免了UsedRange 的问题以及您不知道哪一行可能有最后一列(以及哪一列可能有最后一行)的问题。适应你的目的:

Option Explicit
Sub LastRowCol()

Dim LastRow As Long, LastCol As Long

With Worksheets("sheet1") 'or any sheet
    If Application.WorksheetFunction.CountA(.Cells) > 0 Then
        LastRow = .Cells.Find(what:="*", after:=[A1], _
                    LookIn:=xlFormulas, _
                    searchorder:=xlByRows, _
                    searchdirection:=xlPrevious).Row
        LastCol = .Cells.Find(what:="*", after:=[A1], _
                    LookIn:=xlFormulas, _
                    searchorder:=xlByColumns, _
                    searchdirection:=xlPrevious).Column
    Else
        LastRow = 1
        LastCol = 1
    End If
End With

Debug.Print LastRow, LastCol

End Sub

虽然基本技术已被长期使用,但 Siddarth Rout 不久前发布了一个添加 COUNTA 的版本,以解决工作表可能为空的情况——这是一个有用的补充。

【讨论】:

    【解决方案4】:

    如果要将每张工作表上的数据合并到一个 MasterSheet 中,请运行以下脚本。

    Sub CopyRangeFromMultiWorksheets()
        Dim sh As Worksheet
        Dim DestSh As Worksheet
        Dim Last As Long
        Dim CopyRng As Range
    
        With Application
            .ScreenUpdating = False
            .EnableEvents = False
        End With
    
        'Delete the sheet "RDBMergeSheet" if it exist
        Application.DisplayAlerts = False
        On Error Resume Next
        ActiveWorkbook.Worksheets("RDBMergeSheet").Delete
        On Error GoTo 0
        Application.DisplayAlerts = True
    
        'Add a worksheet with the name "RDBMergeSheet"
        Set DestSh = ActiveWorkbook.Worksheets.Add
        DestSh.Name = "RDBMergeSheet"
    
        'loop through all worksheets and copy the data to the DestSh
        For Each sh In ActiveWorkbook.Worksheets
            If sh.Name <> DestSh.Name Then
    
                'Find the last row with data on the DestSh
                Last = LastRow(DestSh)
    
                'Fill in the range that you want to copy
                Set CopyRng = sh.Range("A1:G1")
    
                'Test if there enough rows in the DestSh to copy all the data
                If Last + CopyRng.Rows.Count > DestSh.Rows.Count Then
                    MsgBox "There are not enough rows in the Destsh"
                    GoTo ExitTheSub
                End If
    
                'This example copies values/formats, if you only want to copy the
                'values or want to copy everything look at the example below this macro
                CopyRng.Copy
                With DestSh.Cells(Last + 1, "A")
                    .PasteSpecial xlPasteValues
                    .PasteSpecial xlPasteFormats
                    Application.CutCopyMode = False
                End With
    
                'Optional: This will copy the sheet name in the H column
                DestSh.Cells(Last + 1, "H").Resize(CopyRng.Rows.Count).Value = sh.Name
    
            End If
        Next
    
    ExitTheSub:
    
        Application.Goto DestSh.Cells(1)
    
        'AutoFit the column width in the DestSh sheet
        DestSh.Columns.AutoFit
    
        With Application
            .ScreenUpdating = True
            .EnableEvents = True
        End With
    End Sub
    
    Function LastRow(sh As Worksheet)
        On Error Resume Next
        LastRow = sh.Cells.Find(What:="*", _
                                After:=sh.Range("A1"), _
                                Lookat:=xlPart, _
                                LookIn:=xlFormulas, _
                                SearchOrder:=xlByRows, _
                                SearchDirection:=xlPrevious, _
                                MatchCase:=False).Row
        On Error GoTo 0
    End Function
    
    
    Function LastCol(sh As Worksheet)
        On Error Resume Next
        LastCol = sh.Cells.Find(What:="*", _
                                After:=sh.Range("A1"), _
                                Lookat:=xlPart, _
                                LookIn:=xlFormulas, _
                                SearchOrder:=xlByColumns, _
                                SearchDirection:=xlPrevious, _
                                MatchCase:=False).Column
        On Error GoTo 0
    End Function
    

    此外,请参阅下面的链接,了解其他一些稍有不同的选项。

    http://www.rondebruin.nl/win/s3/win002.htm

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2014-11-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-01-24
      相关资源
      最近更新 更多