表单

时间:2018-03-23 10:37:00

标签: excel vba excel-vba

我刚刚开始使用VBA,在不同工作表之间复制数据时我遇到了这个错误。

要求是找到特定的数据点块并将它们复制到另一张纸上。

类似FirstRowArrayCol1的变量包含数据点的位置,而i表示列数量。

错误出现在这一行

Set rngDest = wksDest.Range(Cells(i, firstPos))

请检查以下代码。非常感谢任何帮助,谢谢。

Set wksSource = ActiveWorkbook.Sheets("Sheet1")
Set wksDest = ActiveWorkbook.Sheets("Sheet2")
        For Each firstPos In FirstRowArrayCol1
            If firstPos = 0 Then
                Exit For
            End If
            For Each secondPos In SecondRowArrayCol1
                If secondPos = 0 Then
                    Exit For
                End If
                Diff = Abs(firstPos - secondPos)
                If Diff > 0 And Diff <= 5 Then
                    Debug.Print (column3 & firstPos & "," & column3 & secondPos & "," & column4 & firstPos & "," & column4 & secondPos)
                    'Copy Data
                    Set rngSource = wksSource.Range(Cells(i, firstPos), Cells(i + 1, secondPos))
                    rngSource.Range(Cells(i, firstPos), Cells(i + 1, secondPos)).Select
                    rngSource.Copy
                    'Paste Data Values
                    Set rngDest = wksDest.Range(Cells(i, firstPos))
                    rngDest.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False

                End If
            Next secondPos
            For Each secondPos In SecondRowArrayCol2
                If secondPos = 0 Then
                    Exit For
                End If
                Diff = Abs(firstPos - secondPos)
                If Diff > 0 And Diff <= 5 Then
                    Debug.Print (column3 & firstPos & "," & column3 & secondPos & "," & column4 & firstPos & "," & column4 & secondPos)
                    'Copy Data
                    Set rngSource = wksSource.Range(Cells(i, firstPos), Cells(i + 1, secondPos))
                    rngSource.Range(Cells(i, firstPos), Cells(i + 1, secondPos)).Select
                    rngSource.Copy
                    'Paste Data Values
                    Set rngDest = wksDest.Range(Cells(i, firstPos))
                    rngDest.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False

                End If
            Next secondPos
        Next firstPos

2 个答案:

答案 0 :(得分:3)

Worksheet.Range Property接受2个单元格,如

Set rngDest = wksDest.Range(Cells(i, firstPos), Cells(i, firstPos))

或一个地址

Set rngDest = wksDest.Range(Cells(i, firstPos).Address)

但不是1个细胞

Set rngDest = wksDest.Range(Cells(i, firstPos)) 'not valid

因为您可以直接使用Cells

Set rngDest = wksDest.Cells(i, firstPos)

答案 1 :(得分:1)

Set rngDest = wksDest.Range(Cells(i, firstPos))更改为:

Set rngDest = wksDest.Cells(i, firstPos)