根据条件将单元格值相乘时出现错误1004

我有一个macros查看一个单元格的范围。 其他每个单元格都是1或0(符号位)。 根据符号位,下一个单元格(正常数字)乘以1或0.我一直得到运行时错误1004 Application-defined or object-defined error If语句的ElseIf的主体上的1004 Application-defined or object-defined error (指示下面)。 不知道我在做什么错。 我的代码是在“概念certificate”阶段,所以它仍然是非常黑客。

 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 

那是因为你在使用Select 。 显然, SelectActivate不会给你值。 他们select或激活单元格,与使用鼠标手动点击单元格或使用键盘移动/激活单元格不同。 将它们乘以一个值是主要的否定。

您应该查找的Range属性是Value 。 无论如何,我觉得因为有两个循环而让你很难。 你真的应该重新考虑你的devise模式。 无论如何,这是我的方法(我的垂直方向,但看起来像你的是水平的,所以要清楚你到底是什么,所以这是可以调整的)。

 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 

截图:

在这里输入图像说明

让我们知道这是否有帮助。