英文:
Getting 'Runtime error '1004': application-defined or object-defined error' while trying to assign formula to a range
问题
I am getting the "Runtime error '1004': application-defined or object-defined error" when I try to execute the following code, and I have no idea why this is happening.
Dim rangeOfReg As Range
Dim rowOfRegStringfied As String
rowOfRegStringfied = LTrim(Str(rowOfReg))
Set rangeOfReg = Worksheets("Sheet").Range(colOfReg + rowOfRegStringfied)
rangeOfReg.Formula = "=AVERAGEIF(H2:J" + rowOfRegStringfied + ",'Seg a quarta';J2:J" + rowOfRegStringfied + ")"
The value of colOfReg, when it is read is "H", the value of rowOfReg is 20. The error is thrown when this last line is executed.
I have tried not assigning that Range to that variable of type range, but instead calling "Worksheets("Sheet").Range(colOfReg + rowOfRegStringfied)" in the next line but didn't work.
I have also tried replacing commas in the formula being assigned, but the error is still there.
英文:
I am getting the "Runtime error '1004': application-defined or object-defined error" when I try to execute the following code, and I have no idea why this is happening.
Dim rangeOfReg As Range
Dim rowOfRegStringfied As String
rowOfRegStringfied = LTrim(Str(rowOfReg))
Set rangeOfReg = Worksheets("Sheet").Range(colOfReg + rowOfRegStringfied)
rangeOfReg.Formula = "=AVERAGEIF(H2:J" + rowOfRegStringfied + ";'Seg a quarta';J2:J" + rowOfRegStringfied + ")"
The value of colOfReg, when it is read is "H", the value of rowOfReg is 20. The error is thrown when this last line is executed.
I have tried not assigning that Range to that variable of type range, but instead calling "Worksheets("Sheet").Range(colOfReg + rowOfRegStringfied)" in the next line but didn't work.
I have also tried replacing commas in the formula being assigned, but the error is still there.
答案1
得分: 1
在进行@chrisneilsen和@freeflow建议的更正后(所有都需要),您的问题归结为字符串的这一部分:
",'Seg a quarta',J2:J"
正如您所指出的,这需要为
"Seg a quarta"
使用双引号。
在字符串内部插入双引号需要“转义”它,以便Excel不将其解释为字符串的结束。在VBA中,使用两个连续的双引号来转义双引号:
",""Seg a quarta"",J2:J"
因此,完整的语句将是:
rangeOfReg.Formula = "=AVERAGEIF(H2:J" & rowOfRegStringfied & ",""Seg a quarta"",J2:J" & rowOfRegStringfied & ")"
Excel会接受这个字符串而不会报错。
英文:
After making the corrections suggested by @chrisneilsen and @freeflow (all are needed), your issue comes down to this piece of the string:
",'Seg a quarta',J2:J"
As you noted, that requires double quotes for
"Seg a quarta"
Inserting a double quote inside a string requires "escaping" it so Excel doesn't interpret it as the end of the string. In VBA, use two double quotes together to escape the double quote:
",""Seg a quarta"",J2:J"
So the full statement will be:
rangeOfReg.Formula = "=AVERAGEIF(H2:J" & rowOfRegStringfied & ",""Seg a quarta"",J2:J" & rowOfRegStringfied & ")"
Excel accepts that without complaining.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论