简体   繁体   English

从VBA向Excel单元格添加公式

[英]Adding a formula into Excel cell from vba

I have a worksheet labeled my_new_name and want to put in a formula, having looked at other stack overflow threads i have come up with the following: 我有一个标签为my_new_name的工作表,并且想输入一个公式,在查看了其他堆栈溢出线程后,我想到了以下内容:

Set wsDest = Sheets("my_new_name")
wsDest.Range("J2").Formula = "=RIGHT(K2,2)&" / "&MID(K2,5,2)&" / "&LEFT(K2,4)"
wsDest.Range("J2").Select
Selection.AutoFill Destination:=Range("J2:J")

However this doesn't work and the error comes up with a 'type mismatch' 但是,这不起作用,并且错误带有“类型不匹配”

Any help would be great 任何帮助都会很棒

Provided that the Formula output you're after reads as =RIGHT(K2,2)&"/"&MID(K2,5,2)&"/"&LEFT(K2,4) , you'll have to escape the double quotes in your VBA line. 假设您获得的公式输出为=RIGHT(K2,2)&"/"&MID(K2,5,2)&"/"&LEFT(K2,4) ,则必须转义双引号在您的VBA行中。

wsDest.Range("J2").Formula = "=RIGHT(K2,2)&" / "&MID(K2,5,2)&" / "&LEFT(K2,4)" (throws type mismatch) wsDest.Range("J2").Formula = "=RIGHT(K2,2)&" / "&MID(K2,5,2)&" / "&LEFT(K2,4)" (抛出类型不匹配)

Should be: 应该:

wsDest.Range("J2").Formula = "=RIGHT(K2,2)&"" / ""&MID(K2,5,2)&"" / ""&LEFT(K2,4)" (doesn't error) wsDest.Range("J2").Formula = "=RIGHT(K2,2)&"" / ""&MID(K2,5,2)&"" / ""&LEFT(K2,4)" (不错误)

Edit: Also, as per comment section you'll need to specify the end row afterwards (J2:J####) - where ### is a row number. 编辑:此外,根据注释部分,您需要在此后指定结束行(J2:J####) -其中###是行号。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM