设置变量时的运行时错误“1004”,应用程序定义或对象定义的错误= cell.offset

时间:2016-11-29 19:20:06

标签: excel vba offset

这是我的代码。它运行从Cell L1开始的值列表,在另一个工作表中找到它们,然后找到一个偏移单元格。如果该单元格包含"TEMPLATE",则从原始列表中删除该值。

Sub Removetemplate()

Dim x As Variant
Dim myString As String
Dim temprng As Range
Dim cell As Object

  ' Set numrows = number of rows of data.
  Worksheets("WorkingSO").Activate
  NumRows = Range("L2", Range("L2").End(xlDown)).Rows.Count
  ' Select cell L2.
  Set SORNG = Range("L2")
  SORNG.Select
  ' Establish "For" loop to loop "numrows" number of times.
  Worksheets("Sales Orders").Activate
  For x = 1 To NumRows

        For Each cell In Sheet1.Cells
                If cell.Value = SORNG.Value Then
                    Set temprng = cell.Offset(28, -17)
                    myString = temprng.Value
                        If InStr(myString, "TEMPLATE") > 0 Then
                            SORNG.ClearContents
                        End If
                End If
        Next



     ' Selects cell down 1 row from active cell.
     Set SORNG = SORNG.Offset(1, 0)
  Next



End Sub

1004 error位于Set temprng = cell.Offset(28, -17)行。我不是100%肯定,但我相信它第一次通过,但在第二次循环失败。

1 个答案:

答案 0 :(得分:0)

因为For Each cell In Sheet1.Cells遍历 Sheet1的所有单元格,因此它也会遍历属于第1列到第17列的单元格,导致cell.Offset(28, -17)失败,因为它试图达到“负列”单元格

此外,您必须避免Activate / Select编码习惯并使用完全合格的范围参考

试试这段代码:

Option Explicit

Sub Removetemplate()
    Dim SOCell As Range, WSOCell As Range
    Dim WSORng As Range

    ' Set numrows = number of rows of data.
    With Worksheets("WorkingSO")
        Set WSORng = .Range("L2", .Range("L2").End(xlDown)) 'set "WorkingSO" worksheet range to loop through
    End With

    With Worksheets("Sales Orders") '<--| reference "Sales Orders" worksheet
        For Each WSOCell In WSORng '<--| loop through WSORng cells
            For Each SOCell In .Columns("R").SpecialCells(xlCellTypeConstants) '<--| loop through currently referenced worksheet (i.e. "Sales Orders") column "R" cells with any constant value
                If SOCell.Value = WSOCell.Value Then '<--| if current "Sales Orders" cell value matches current "WorkingSO" one
                    If InStr(SOCell.Offset(28, -17), "TEMPLATE") > 0 Then WSOCell.ClearContents '<--| if "Sales Orders" cell offsetted 28 rows down and 17 columns left form current one has "TEMPLATE", then clear current "WorkingSO" cell
                End If
            Next
        Next
    End With
End Sub

您必须将.Columns("R")更改为实际的“销售订单”工作表列索引,以便在

中查找“WorkingSO”列“L”值