![](/img/trans.png)
[英]excel-vba How to make macro replace 5 last character and add it into new colomn until last row
[英]Excel-Vba : Code for Applying Formula until Last Row not working
如果这似乎是一个简单的问题,我是 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""))))"
感谢所有的帮助
@麦克风; 你的问题在这一行:
LastRow = Sheets("DLASpotPlacement").Cells(Rows.Count, 1).Rows
您将LastRow
数组,而不是数字。 此外,不是 Double 而是 Iteger(数学上)。 但是,Integer 数据类型太小,如果将其声明为“As Integer”,则会出现“溢出”错误。 以下是使其全部工作所需的两项更改:
Dim LastRow As Long
LastRow = Sheets("DLASpotPlacement").Rows.Count
...
发生错误的原因有两个:
您在LastRow
Calculation 中忘记了End(xlUp)
,例如:
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
是一个FormulaLocal
记住的好“技巧”。
对于 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
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.