从其他工作表运行时运行时错误“1004”

时间:2017-09-09 07:21:15

标签: excel vba excel-vba

我在Excel中遇到VBA问题。我有一个组合框,可以选择变量fylke,当我更改组合框时,我正在运行此宏。

Sub findData()

Dim fylke As String
Dim finalRow As Integer
Dim i As Integer

Sheets("Valg").Range("Q2:AB28").ClearContents

fylke = Sheets("Valg").Range("P32")
finalRow = Sheets("Valg").Range("B10000").End(xlUp).Row

For i = 2 To finalRow
    If Sheets("Valg").Cells(i, 2) = fylke Then
        Sheets("Valg").Range(Cells(i, 3), Cells(i, 13)).Copy
        Sheets("Valg").Range("Q100").End(xlUp).Offset(1, 0).PasteSpecial xlPasteFormulasAndNumberFormats
    End If
Next i

End Sub

当我选择工作表“Valg”时运行宏时,宏按预期工作,但是当我从组合框所在的工作表运行宏时,我收到错误。

  

运行时错误'1004':应用程序定义的错误或对象定义的错误

错误调试到这行代码:

Sheets("Valg").Range(Cells(i, 3), Cells(i, 13)).Copy

2 个答案:

答案 0 :(得分:3)

Sheets("Valg").Range(Cells(i, 3), Cells(i, 13)).Copy不完全符合“Valg”表格,您还需要使用表格Cells来限定Range

您应该使用With Sheets("Valg")语句使代码更短更清晰。

此外,在循环遍历行并查找最后一行时,应使用Long代替Interger

尝试以下代码:

Option Explicit

Sub findData()

Dim fylke As String
Dim finalRow As Long
Dim i As Long

With Sheets("Valg")
    .Range("Q2:AB28").ClearContents

    fylke = .Range("P32")
    finalRow = .Range("B10000").End(xlUp).Row

    For i = 2 To finalRow
        If .Cells(i, 2) = fylke Then
            .Range(.Cells(i, 3), .Cells(i, 13)).Copy
            .Range("Q100").End(xlUp).Offset(1, 0).PasteSpecial xlPasteFormulasAndNumberFormats
        End If
    Next i
End With

End Sub

答案 1 :(得分:-3)

您必须首先激活“Valg”表单

<强>代码

Sub findData()

Dim fylke As String
Dim finalRow As Integer
Dim i As Integer

Sheets("Valg").Range("Q2:AB28").ClearContents

fylke = Sheets("Valg").Range("P32")
finalRow = Sheets("Valg").Range("B10000").End(xlUp).Row



For i = 2 To finalRow
    If Sheets("Valg").Cells(i, 2) = fylke Then
    Sheets("Valg").Activate
        Range(Cells(i, 3), Cells(i, 13)).Copy
        Range("Q100").End(xlUp).Offset(1, 0).PasteSpecial xlPasteFormulasAndNumberFormats
    End If
Next i

End Sub
相关问题