我在这里得到了一些帮助,在vba中将公式声明为常量。我有大约十个公式,主题上都有类似的变化。我已经设置了9个并且它们正常工作,下面的一个会引发运行时错误(运行时错误'1004';应用程序定义或对象定义错误。
Option Explicit
Public Const csFORMULA = "=CONCATENATE(""AVABIS"",IF(I2=0,"""",CONCATENATE(UPPER(AlphaNumericOnly(LEFT(I2,3))),UPPER(AlphaNumericOnly(RIGHT(I2,3))))),IF(O2=0,"""",UPPER(AlphaNumericOnly(SUBSTITUTE(O2,""0"","""")))),IF(R2=0,"""",UPPER(AlphaNumericOnly(SUBSTITUTE(R2,""0"","""")))),IF(W2=0,"""",UPPER(AlphaNumericOnly(SUBSTITUTE(W2,""0"","")))),IF(AB2=0,"""",AlphaNumericOnly(SUBSTITUTE(AB2,""0"",""""))),IF(AC2=0,"""",AlphaNumericOnly(SUBSTITUTE(AC2,""0"",""""))),IF(AD2=0,"""",SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(AD2,""-"",""X""),""."",""Y""),""0"",""Z"")),IF(AF2=0,"""",SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(AF2,""-"",""X""),""."",""Y""),""0"",""Z"")),IF(AH2=0,"""",SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(AH2,""-"",""X""),""."",""Y""),""0"",""Z""))))"
Sub AvivaBIS()
Dim lr As Long
Dim cl As Range
Dim rng As Range
Dim mssg As String
Dim ws As Worksheet
Application.ScreenUpdating = False
Set ws = ActiveSheet
With ws
lr = .Range("I" & Rows.Count).End(xlUp).Row
'add the formula to generate the unique key
Range("B2:B" & lr).Formula = csFORMULA
Range("B2:B" & lr) = Range("B2:B" & lr).Value
End With
Set rng = Nothing
Set ws = Nothing
Application.ScreenUpdating = True
End Sub
我已从上面删除了其他非基本代码以简化我的问题。
到目前为止我采取的步骤:
尝试在表格中直接粘贴原始公式 - 这是有效的。
尝试将声明的公式替换为简单的(例如A1 + A2) - 这是有效的。
仔细检查引号,看看我的号码是否正确 - 这些似乎很好。
从我创建的其他公式复制了另一个非常相似的公式 - 这也有效。
我会非常感激地收到任何有关我可以解决此问题的建议。有没有办法在它抛出运行时错误时获取更多信息?
一如既往地感谢您花时间去看。
答案 0 :(得分:2)
你错过了一组空字符串双引号(在公式中途的W2之后),并在最后有一个额外的结束括号。
Public Const csFORMULA = "=CONCATENATE(""AVABIS"",IF(I2=0,"""",CONCATENATE(UPPER(AlphaNumericOnly(LEFT(I2,3))),UPPER(AlphaNumericOnly(RIGHT(I2,3))))),IF(O2=0,"""",UPPER(AlphaNumericOnly(SUBSTITUTE(O2,""0"","""")))),IF(R2=0,"""",UPPER(AlphaNumericOnly(SUBSTITUTE(R2,""0"","""")))),IF(W2=0,"""",UPPER(AlphaNumericOnly(SUBSTITUTE(W2,""0"","""")))),IF(AB2=0,"""",AlphaNumericOnly(SUBSTITUTE(AB2,""0"",""""))),IF(AC2=0,"""",AlphaNumericOnly(SUBSTITUTE(AC2,""0"",""""))),IF(AD2=0,"""",SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(AD2,""-"",""X""),""."",""Y""),""0"",""Z"")),IF(AF2=0,"""",SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(AF2,""-"",""X""),""."",""Y""),""0"",""Z"")),IF(AH2=0,"""",SUBSTITUTE(SUBSTITUTE(SUBSTITUTE(AH2,""-"",""X""),""."",""Y""),""0"",""Z"")))"