运行时错误'1004':应用程序或对象定义错误
嘿,我无法找出为什么我的代码无效。我知道它在公式右侧的某个地方。我已经为你突出了这个错误。
Private Sub CommandButton1_Click() 'accept button
Blank:
machine = TextBox1.Value
rates = TextBox2.Value
If machine = "" Then 'if blank
MsgBox ("Please type in a machine name.")
GoTo DONE
ElseIf rates = "" Then 'if rates is blank
MsgBox ("Please type in a rate for machine.")
GoTo DONE
End If
For i = 1 To 50 'search database
If LCase(Worksheets("database").Cells.Range("B2").Offset(0, i)) = LCase(machine) Then 'if name is in database
MsgBox (machine & " is already in database. Choose another name.")
GoTo DONE
ElseIf IsEmpty(Worksheets("database").Cells.Range("B2").Offset(0, i)) Then 'if it's not
Range("B:B").Offset(0, i).Select
Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove
Worksheets("database").Cells.Range("B2").Offset(0, i) = machine
Worksheets("database").Cells.Range("B2").Offset(0, i).HorizontalAlignment = xlLeft
Worksheets("database").Cells.Range("B2").Offset(-1, i) = rates
For j = 1 To 50
If LCase(Range("A1").Offset(j, 0)) = "total hours" Then
ActiveSheet.Range("B1").Offset(j, i).Formula = "=sum(" & Range(Cells(3, i + 2), Cells(j, i + 2)).Address(False, False) & ")"
ActiveSheet.Range("B1").Offset(1 + j, i).Formula = "=product(sum(" & ActiveSheet.Range(Cells(3, i + 2), Cells(j, i + 2)).Address(False, False) & "," & ActiveSheet.Range(Cells(1, 2 + i)) & ")"
GoTo Cancel
End If
Next j
GoTo Cancel
End If
Next i
Cancel:
DONE:
End Sub
我与其他人分开的那条线是有问题的。
谢谢!
答案 0 :(得分:0)
很难知道你没有描述你想要做什么。但也许:
"=product(sum(" & ActiveSheet.Range(Cells(3, I + 2), Cells(J, I + 2)).Address(False, False) & "," & ActiveSheet.Cells(1, 2 + I).Address & "))"
答案 1 :(得分:0)
您需要自行分析线条的每个部分,以查看导致错误的原因。然后在验证零件后将它们放在一起。
Dim HoursRangeAddress As String
Dim RateRangeAddress As String
HoursRangeAddress = ActiveSheet.Range(Cells(3, i + 2), Cells(j, i + 2)).Address(False, False)
RateRangeAddress = ActiveSheet.Cells(1, i + 2).Address
Debug.Print HoursRangeAddress
Debug.Print RateRangeAddress
ActiveSheet.Range("B1").Offset(1 + j, i).Formula = _
"=product(sum(" & HoursRangeAddress & ")," & RateRangeAddress & ")"
总结之后你错过了一个括号)。但这也导致了错误:ActiveSheet.Range(Cells(1, 2 + i))
请尝试此操作:ActiveSheet.Cells(1, 2 + i).Address
使用R1C1表示法:您应该学习R1C1表示法。一旦熟悉它,您的代码就更容易编写和阅读。您可以使用以下一行替换上面的所有代码行:
ActiveSheet.Range("B1").Offset(1 + j, i).FormulaR1C1 = "=R1C*R[-1]C"
我现在明白,您正试图将第一行的比率乘以该公式上方一行的总小时数。
在这种情况下使用R1C1表示法要好得多。您可以完全避免为公式创建字符串地址。您的公式变得非常简单易读。