我是VBA的新手,很抱歉,这似乎是一个简单的问题。
我正在尝试创建一个宏,该宏将在表格中形成并包含几个公式,但是当我尝试在最后一行之前包含该公式时,出现错误“运行时错误1004-应用程序定义或对象以下代码显示“已定义的错误”:
ActiveSheet.Range("U2:U" & LastRow).Formula = "=L2/86400"
如果我将“最后一行”更改为数字,则宏正常工作。下面是完整的代码。
Sheets("DLASpotPlacement").Select
Dim LastRow As Double
LastRow = Sheets("DLASpotPlacement").Cells(Rows.Count, 1).Rows
Range("A1").Select
ActiveSheet.Range("U:U, V:V, W:W").NumberFormat = "[h]:mm:ss;@"
ActiveSheet.Range("U2:U" & LastRow).Formula = "=L2/86400"
ActiveSheet.Range("V2:V" & LastRow).Formula = "=VALUE(H2)"
ActiveSheet.Range("W2:W" & LastRow).FormulaLocal = "=IF(AND(H2>0,0416666666666667;H2<=0,249988425925926);""01 - 06"";IF(AND(H2>=0,25;H2<0,4166551);""06 - 10"";IF(AND(H2>=0,4166667;H2<0,4999884);""10 - 12"";IF(AND(H2>=0,5;H2<0,7499884);""12 - 18"";""18 - 01""))))"
感谢所有帮助
答案 0 :(得分:1)
@Mike;您的问题在这一行:
LastRow = Sheets("DLASpotPlacement").Cells(Rows.Count, 1).Rows
您将LastRow
设置为数组,而不是数字。此外,(不是数学上的)Double而是Iteger。但是,Integer数据类型太小,如果将其声明为“ As Integer”,则会出现“ Overflow”错误。要使它们全部起作用,这是两个更改:
Dim LastRow As Long
LastRow = Sheets("DLASpotPlacement").Rows.Count
...
答案 1 :(得分:1)
由于两个原因而发生错误:
您在End(xlUp)
计算中忘记了LastRow
,例如:
LastRow = Sheets("DLASpotPlacement").Cells(Rows.Count, 1).End(xlUp).Row
,并且必须声明为整数,例如:
Dim LastRow as Long
Option Explicit
Sub CopyFormulas()
Const cCol As Variant = "A" ' Last Row Column Letter/Number
Const cFirstR As Long = 2 ' First Row Number
Dim LastRow As Long ' Last Row Number
With ThisWorkbook.Worksheets("DLASpotPlacement")
LastRow = .Cells(.Rows.Count, cCol).End(xlUp).Row
'.Cells(1, cCol).Select ' uncomment if necessary
' You don't need to format the entire columns.
.Range("U" & cFirstR & ":W" & LastRow).NumberFormat = "[h]:mm:ss;@"
.Range("U" & cFirstR & ":U" & LastRow).Formula = "=L2/86400"
.Range("V" & cFirstR & ":V" & LastRow).Formula = "=VALUE(H2)"
.Range("W" & cFirstR & ":W" & LastRow).FormulaLocal = _
"=IF(AND(H2>0,0416666666666667;H2<=0,249988425925926);""" _
& "01 - 06"";IF(AND(H2>=0,25;H2<0,4166551);""06 - 10"";IF(" _
& "AND(H2>=0,4166667;H2<0,4999884);""10 - 12"";IF(AND(H2>=0" _
& ",5;H2<0,7499884);""12 - 18"";""18 - 01""))))"
End With
End Sub
使用FormulaLocal
是一个不错的“技巧”。
答案 2 :(得分:0)
对于LastRow,请使用Worksheet.UsedRange属性。
您还可以使用Range.Resize属性选择范围,然后将“选择”替换为“具有”。
Dim LastRow As Double
With Sheets("DLASpotPlacement")
LastRow = .UsedRange.Rows.count
.Range("U:W").NumberFormat = "[h]:mm:ss;@"
.Range("U1").Resize(LastRow - 1).Formula = "=L2/86400"
.Range("V1").Resize(LastRow - 1).Formula = "=VALUE(H2)"
.Range("W1").Resize(LastRow - 1).FormulaLocal = "..."
End With