Excel VBA - 如何使用不同的子例程从一张工作簿逐行复制到另一个工作簿的工作表

时间:2018-03-09 07:08:06

标签: excel vba excel-vba excel-2016

我正在尝试将数据从一张工作簿复制到另一个工作簿,但是代码显示错误1004.这是我在子例程的For循环中遇到错误的代码findDuplicates()

Option Explicit

Sub GenerateErrorSheet()
   Dim MyBook As Workbook
   Dim newBook As Workbook
   Dim FileNm As String
   Dim rowCount As Integer

   Set MyBook = ThisWorkbook
   rowCount = 1

   FileNm = ThisWorkbook.Path & "\" & "ErrorSheet-" & Date & ".xls"
   Set newBook = Workbooks.Add

   With newBook

      Call findDuplicates(Worksheets("pid"), "PID Generator", rowCount,newBook.Worksheets("Sheet1"))
      rowCount = rowCount + 4
      'Call findDuplicates(Worksheets("behavioural"), "Behavioural Measurement")
      'rowCount = rowCount + 4
      'Call findDuplicates(Worksheets("physical"), "Physical Measurement")
      'rowCount = rowCount + 4
      'Call findDuplicates(Worksheets("biochemical"), "Biochemical Measurement")
      'Save new wb with XLS extension
      .SaveAs Filename:=FileNm, FileFormat:=xlNormal, CreateBackup:=False

      .Close Savechanges:=False
   End With
   MsgBox "Error Sheet Generated Successfully." & vbNewLine & "Name Of Sheet - ErrorSheet-" & Date & ".xls" & vbNewLine & "Saved Location - " & FileNm
End Sub

我的findDuplicates子程序,它在for循环中给出错误

Sub findDuplicates(ByVal sheet As Worksheet, name As String, ByRef row As Integer, ByVal Sheet2 As Worksheet)
   Dim i As Integer
   Dim numRow As Integer
   numRow = sheet.Range("J2", sheet.Range("J2").End(xlDown)).Rows.Count

   With Sheet2
       Range(Cells(row, "A"), Cells(row, "L")).MergeCells = True
       With Cells(row, "A")
           .Font.name = "Bell MT"
           .Font.FontStyle = "Bold Italic"
           .Font.Size = 20
           .Font.Color = RGB(255, 99, 71)
           .Value = "Multiple Forms Found in " & name & " for single household"
       End With
       row = row + 1
   End With
   For i = 1 To numRow
        sheet.Rows("i").Copy Sheet2.Rows("row")
        row = row + 1
   Next i
End Sub

错误显示为 - Error Image

错误之前的本地值 - Locals Image

1 个答案:

答案 0 :(得分:0)

我猜测它是Sheet2.Rows(" row")。难道这不仅仅是Sheet2.Rows(行)吗?

编辑:Sheet.Rows(" i")可能是sheet.rows(i)。