VBA Autofill语法错误求助:Sheet1用Index-Match填充A-E列数据
问题解决:VBA Autofill语法错误修复
错误核心原因
你的代码主要问题出在Autofill语句的变量引用错误,把变量名当成字符串进行拼接,同时存在几个细节问题:
- 变量名大小写不统一(
emptyrow和Emptyrow),虽VBA不区分大小写,但易引发混淆 Range("A" & Emptyrow, "E" & "Emptyrow")中,"Emptyrow"是字符串而非变量,应改为"E" & emptyrow- 目标区域
Range("A" & lastrow, "E" & "lastrow")同理,"lastrow"需改为变量引用lastrow - 未指定工作表的
Range可能引用当前激活表,建议明确指定Sheets("Sheet1")
修正后的代码
Dim lastrow As Long lastrow = Sheets("Sheet1").Range("F" & Rows.Count).End(xlUp).Row Dim emptyrow As Long emptyrow = Sheets("Sheet1").Range("A" & Rows.Count).End(xlUp).Row ' 明确指定工作表,避免激活表干扰 With Sheets("Sheet1") ' 写入首行公式 .Range("A" & emptyrow).FormulaR1C1 = _ "=INDEX(INDIRECT('Control Panel'!R35C3),MATCH(RC6,INDIRECT('Control Panel'!R36C3),0),MATCH(R1C,INDIRECT('Control Panel'!R37C3),0))" ' 先将公式横向填充到E列当前行 .Range("A" & emptyrow).AutoFill Destination:=.Range("A" & emptyrow & ":E" & emptyrow), Type:=xlFillDefault ' 再将整行公式纵向填充到lastrow行 .Range("A" & emptyrow & ":E" & emptyrow).AutoFill Destination:=.Range("A" & emptyrow & ":E" & lastrow), Type:=xlFillDefault End With
高效优化方案
不需要Autofill,直接批量写入公式效率更高:
Dim lastrow As Long lastrow = Sheets("Sheet1").Range("F" & Rows.Count).End(xlUp).Row Dim emptyrow As Long emptyrow = Sheets("Sheet1").Range("A" & Rows.Count).End(xlUp).Row ' 直接给A-E列批量设置公式 With Sheets("Sheet1").Range("A" & emptyrow & ":E" & lastrow) .FormulaR1C1 = "=INDEX(INDIRECT('Control Panel'!R35C3),MATCH(RC6,INDIRECT('Control Panel'!R36C3),0),MATCH(R1C,INDIRECT('Control Panel'!R37C3),0))" ' 可选:将公式转成值,提升表格性能 .Value = .Value End With
内容的提问来源于stack exchange,提问作者vjr2109
相关产品推荐
相关产品推荐

