运行代码时,它返回 - 范围类的自动填充方法在代码的最后一行失败:VBA
Posted
技术标签:
【中文标题】运行代码时,它返回 - 范围类的自动填充方法在代码的最后一行失败:VBA【英文标题】:When running the code it return a - Autofill method of range class failed at last line of the code : VBA 【发布时间】:2021-06-14 03:56:16 【问题描述】:我是 VBA 新手,我无法理解我的代码在哪里出错。我收到消息"Autofill method of Range class failed"
。请帮我解决
代码:
Sub SomeName()
Dim lRow As Long
Dim wb As Workbook: Set wb = ThisWorkbook
Dim wkSheet As Worksheet
Set wkSheet = wb.ActiveSheet
lRow = wkSheet.Range("G" & wkSheet.Rows.Count).End(xlUp).Row
Sheets("MilestoneStatus").Select
lRow = wkSheet.Range("G" & wkSheet.Rows.Count).End(xlUp).Row
wkSheet.Range("H1").Formula = "=IF(ISBLANK(RC[-1]),"""",IF(DAYS(TODAY(),RC[-1])<0,CONCATENATE(""Due in "",-DAYS(TODAY(),RC[-1]),""DAYS""),IF(DAYS(TODAY(),RC[-1])>0,CONCATENATE(""OVERDUE"",DAYS(TODAY(),RC[-1]),""DAYS""),""Due today"")))"
With wkSheet.Range("H1")
.Formula = Range("H1").Formula
.AutoFill Destination:=Range.Offset(0, 0).Resize(lRow)
End With
End Sub
【问题讨论】:
【参考方案1】:您不需要太多的操作和变量来获得您想要的结果,包括 .AutoFill。试试这个代码:
Sub SomeName()
Dim lRow As Long
With ThisWorkbook.Sheets("MilestoneStatus")
lRow = .Range("G" & .Rows.Count).End(xlUp).Row
.Range("H1").Resize(lRow).FormulaR1C1 = "=IF(ISBLANK(RC[-1]),"""",IF(DAYS(TODAY(),RC[-1])<0,CONCATENATE(""Due in "",-DAYS(TODAY(),RC[-1]),""DAYS""),IF(DAYS(TODAY(),RC[-1])>0,CONCATENATE(""OVERDUE"",DAYS(TODAY(),RC[-1]),""DAYS""),""Due today"")))"
End With
End Sub
如果由于某种原因你仍然需要使用.AutoFill
,你可以这样:
Sub SomeName()
Dim lRow As Long
With ThisWorkbook.Sheets("MilestoneStatus")
lRow = .Range("G" & .Rows.Count).End(xlUp).Row
.Range("H1").FormulaR1C1 = "=IF(ISBLANK(RC[-1]),"""",IF(DAYS(TODAY(),RC[-1])<0,CONCATENATE(""Due in "",-DAYS(TODAY(),RC[-1]),""DAYS""),IF(DAYS(TODAY(),RC[-1])>0,CONCATENATE(""OVERDUE"",DAYS(TODAY(),RC[-1]),""DAYS""),""Due today"")))"
.Range("H1").AutoFill Destination:=.Range("H1").Resize(lRow)
End With
End Sub
我也建议大家关注How to avoid using Select in Excel VBA
【讨论】:
以上是关于运行代码时,它返回 - 范围类的自动填充方法在代码的最后一行失败:VBA的主要内容,如果未能解决你的问题,请参考以下文章