Excel visual basic 1004 error, method 'value' of object 'range' failed

自作多情 提交于 2019-12-11 12:19:06

问题


I made a little add-in for excel. But for some reason it fails. After a fresh startup of excel it works fine, however when I copy paste text into excel and try to run it, it gives me the error: run-time '1004' , method 'Value' of object 'range' failed.

What I'm trying to do, is quit simple. I like building formula's like : (B5+B6)/2 without the use of an '=' in front so Excel doesn't calculate these expressions. I end up with one big column, and after I am finished I would like to select the first cell of the column with calculations, activate my add-in and he puts an '=' in front and loops downward untill an empty cell. This way each cell in my column is now calculated.

I am lost, can you help me ?

Sub makeFormula()
Do
ActiveCell.Value = "=" & ActiveCell.Value
ActiveCell.Offset(1, 0).Select
Loop While ActiveCell.Value <> Empty
end Sub

回答1:


I've found the solution, with debugging I found out that commas are the problem, So I change the comma to a dot, and then calculate. And now it works like a charm.

Sub makeFormula()
Dim Temp As String
Do
    Temp = ActiveCell.Value2
    Temp = Replace(Temp, ",", ".", 1)
    ActiveCell.Formula = "=" & Temp
    ActiveCell.Offset(1, 0).Select
Loop While ActiveCell.Value2 <> Empty
End Sub

Thanks for all your suggestions.




回答2:


Sub makeFormula()
Dim c as range
Set c = selection.cells(1) 'in case >1 cell is selected
do while len(c.value) > 0
    'need to put quotes around the value if not a number
    'c.Formula = "=""" & c.Value & """"
    'use this if the value is a valid formula without =
    c.Formula = "=" & c.Value 
    Set c=c.Offset(1, 0)
Loop
End Sub



回答3:


You need to pass your value to temporary string variable. Worked for me:

Sub makeFormula()
    Dim Temp As String
    Do
        Temp = ActiveCell.Value2
        ActiveCell.Formula = "=" & Temp
        ActiveCell.Offset(1, 0).Select
    Loop While ActiveCell.Value2 <> Empty
End Sub


来源:https://stackoverflow.com/questions/21790762/excel-visual-basic-1004-error-method-value-of-object-range-failed

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!