基于标准乘以单元格值时出现错误1004

时间:2014-08-15 19:31:46

标签: excel vba excel-vba

我有一个查看一系列单元格的宏。每隔一个单元格为1或0(符号位)。根据符号位,下一个单元格(正常数字)乘以1或0.我在1004 Application-defined or object-defined error ElseIf的主体上得到运行时错误If声明(如下所示)。不确定我做错了什么。我的代码在"概念证明"阶段所以它仍然非常hackish。

Dim N As Long
------------------------------------------
Private Sub CommandButton1_Click()

Dim x As Integer
Dim y As Integer
x = 0
y = 1

N = Application.InputBox(Prompt:="Enter value", Type:=1)
If N > Columns.Count Then
    N = Columns.Count
Else
    For i = 4 To 9999
        Cells(1, i).ClearContents
        Cells(3, i).ClearContents
    Next i
End If

For i = 4 To N + 3
    x = x + y
    Cells(1, i) = x
Next i

For i = 4 To N + 3
    If Cells(2, i) = 1 Then
        Cells(2, i).Offset(0, 1).Select = Cells(2, i).Offset(0, 1).Select * -1
    ElseIf Cells(2, i) = 0 Then

'This is the line with errors vvvvvvvvvvvvvvvvv

        Cells(2, i).Offset(0, 1).Select = Cells(2, i).Offset(0, 1).Select * 1
    End If
Next i

End Sub

1 个答案:

答案 0 :(得分:1)

那是因为你正在使用Select。显然,SelectActivate不会给你价值。他们选择或激活单元格,与使用鼠标手动点击它们或使用键盘或其他方式移动/激活单元格不同。将它们乘以一个值是一个主要的禁忌。

您应该寻找的Range媒体资源是Value。在任何情况下,我认为你因为有两个循环而变得困难。你真的应该重新考虑你的设计模式。在任何情况下,这是我的方法(我的方法是垂直的,但看起来你的是水平的,所以要明确你的结果是什么,这样可以调整)。

Private Sub CommandButton1_Click()

    Dim WS As Worksheet
    Dim LastRow As Long
    Dim Iter As Long
    Dim CurrCell As Range
    Const Col = 1

    With ThisWorkbook
        Set WS = .Sheets("Sheet3") 'Change as necessary.
    End With

    With WS
        LastRow = .Range("A" & .Rows.Count).End(xlUp).Row
        For Iter = 1 To LastRow 'Change as necessary.
            Set CurrCell = .Cells(Iter, Col)
            Select Case CurrCell.Value
                Case 1
                    CurrCell.Offset(0, 1).Value = (CurrCell.Offset(0, 1).Value * (-1))
                Case 0
                    CurrCell.Offset(0, 1).Value = (CurrCell.Offset(0, 1).Value * 1) 'Is this even necessary? It's an identity.
            End Select
        Next
    End With

End Sub

截图:

enter image description here

如果有帮助,请告诉我们。