对象'_Global'的方法'范围'失败错误1004

时间:2016-11-11 21:28:36

标签: vba excel-vba excel

我查看了这个问题的几个解决方案,并尝试了其中一些解决方案,包括前缀“。”到关键字单元格但没有工作

以下是我的潜艇

Sub GJK()
Dim port_total_periodic_rows As Worksheet

Dim Target As Worksheet
Dim i As Integer
Dim J As Integer
Dim DTCPYCTR As Integer
Dim DTPSTCTR As Integer
Dim FNDPSTCTR As Integer>
Dim FNDCPYCTR As Integer

DTCPYCTR = 5
FNDCPYCTR = 7
DTPSTCTR = 2
FNDPSTCTR = 2

For i = 1 To 138
    For J = 1 To 113
    Sheets("port_total_periodic_rows").Cells(DTCPYCTR, 3).Copy
    Sheets("Target").Cells(DTPSTCTR, 1).PasteSpecial Paste:=xlPasteValues
    Sheets("port_total_periodic_rows").Range(Cells(FNDCPYCTR, 2), _
                                               Cells(FNDCPYCTR, 4)).Copy
    Sheets("Target").Range(Cells(FNDPSTCTR, 2), _
                 Range(FNDPSTCTR,4)).PasteSpecial Paste:=xlPasteValues

    FNDPSTCTR = FNDPSTCTR + 1
    FNDCPYCTRT = FNDCPYCTR + 1
    DTPSTCTR = DTPSTCTR + 1

    Next

    DTCPYCTR = DTCPYCTR + 1 
Next 

End Sub

1 个答案:

答案 0 :(得分:3)

默认情况下,Cells()引用ActiveSheet,因此如果活动工作表不是“port_total_periodic_rows”,则会失败:

Sheets("port_total_periodic_rows").Range(Cells(FNDCPYCTR, 2), _
                                           Cells(FNDCPYCTR, 4)).Copy

应该是:

With Sheets("port_total_periodic_rows")
    .Range(.Cells(FNDCPYCTR, 2), .Cells(FNDCPYCTR, 4)).Copy
End with 

类似的事情也适用于以下行。

最好还是使用Long代替Integer来避免可能的溢出问题。