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

时间:2017-11-28 11:45:22

标签: excel vba excel-vba

我试图复制多个范围,然后将其粘贴到word。我已设置多个范围,然后使用Union前缀加入。但每次我运行代码我得到错误代码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      

2 个答案:

答案 0 :(得分:2)

你依赖于ActiveSheetSet Set sht = Worksheets("Calculations") If,你需要在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 并复制其中的每一个:

ax=df["D"].plot.line(ax=ax, color='red')
ax=df[["A", "B", "C"]].plot.area(ax=ax)

答案 1 :(得分:0)

当你没有定义范围/单元格的工作表时,

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)

在您的情况下,您可能尝试制作Union()不同Worksheets()的范围。因此,它会出现1004错误:

E.g。这给出了错误:

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

这没关系,因为工作表是相同的:

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