复制多个范围但得到运行时错误1004

我试图复制多个范围,然后将其粘贴到单词。 我已经设置了多个范围,然后用Union前缀join。 但每次我运行的代码,我得到错误代码1004.范围mRange已黯淡和设置,我已经尝试更改名称,指定表等。 但它仍然不起作用。

任何帮助,将不胜感激!

 Sub ExportToWord() 'Option Explicit Dim WordApp As Word.Application Dim myDoc As Word.Document Dim WordTable As Word.Table Dim SrcePath As String Dim sht As Worksheet Dim LastRow As Long Dim LastColumn As Long Dim StartCell As Range Dim range1 As Range, range2 As Range, range3 As Range, mRange As Range If Cells(4, 17) = True Then 'Copies the specified range in excel Set sht = Worksheets("Calculations") Set StartCell = Range("M3") 'Refresh UsedRange Worksheets("Calculations").UsedRange 'Find Last Row LastRow = Range("M" & Rows.Count).End(xlUp).Row 'Select Range sht.Range("M3:R" & LastRow).Copy Else 'copies the specified range Set range1 = Range("M3:R5") Set range2 = Range("M6:O" & Range("O" & Rows.Count).End(xlUp).Row) Set range3 = Range("Q6:R" & Range("R" & Rows.Count).End(xlUp).Row) Set mRange = Union(range1, range2, range3) mRange.Copy End If 

你在ActiveSheet上依赖很多,你也可以在你的Set sht = Worksheets("Calculations")If你需要在第一个之前把它取出来,请看下面的代码:

 ' ===== First: set the worksheet object ===== Set sht = Worksheets("Calculations") With sht If .Cells(4, 17) = True Then 'Copies the specified range in excel Set StartCell = .Range("M3") 'Find Last Row LastRow = .Range("M" & .Rows.Count).End(xlUp).Row 'Select Range .Range("M3:R" & LastRow).Copy Else 'copies the specified range Set range1 = .Range("M3:R5") Set range2 = .Range("M6:O" & .Range("O" & .Rows.Count).End(xlUp).Row) Set range3 = .Range("Q6:R" & .Range("R" & .Rows.Count).End(xlUp).Row) Set mRange = Union(range1, range2, range3) mRange.Copy End If End With 

为了复制多个Selections (不同的范围区域),您将必须遍历Areas并复制它们中的每一个:

  Dim C As Range For Each C In mRange.Areas C.Copy ' do here your Paste section Next C 

当你没有定义范围/单元格的工作表时, 1004经常发生。 如果没有定义,Excel引用ActiveSheet作为父项,这并不总是打算。

确保定义每一RowColumnCellRange与其父。 喜欢这个:

 Set sht = Worksheets("Calculations") Set StartCell = sht.Range("M3") 'Find Last Row LastRow = sht.Range("M" & sht.Rows.Count).End(xlUp).Row Set range2 = sht.Range("M6:O" & sht.Range("O" & sht.Rows.Count).End(xlUp).Row) 

或者你可以使用With Worksheets("Calculations") ,它会更好看:

 With Worksheets("Calculations") LastRow = .Range("M" & .Rows.Count).End(xlUp).Row Set range2 = .Range("M6:O" & .Range("O" & .Rows.Count).End(xlUp).Row) 

在你的情况下,你可能正在尝试在不同的Worksheets()上创build一个范围的Union() Worksheets() 。 因此,它给了1004错误:

例如,这给错误:

 set k = Union(Worksheets(1).Range("A1"),Worksheets(2).Range("A2")) 

这是可以的,因为工作表是一样的:

 set k = Union(Worksheets(1).Range("A1"),Worksheets(1).Range("A2"))