how to write results of a formula directly into an excel range by VBA code

不羁的心 提交于 2019-12-11 16:02:22

问题


I have a series of functions for each of listobject columns. The file is heavy and crashing, so I want just to keep the results of each formula as static values. I can allocate formula to the range and ask excel to convert the range to value. But I am wondering if there is a way to ask VBA to write only the static values in the range instead of the formula itself. Here is what I have so far:

Sub calculate2()
Dim i As Long, t As Long
t = Timer
    With Sheet3.ListObjects(1)
      For i = 3 To 9
         .ListColumns(i).DataBodyRange.ClearContents
         .Range.Cells(2, i).Formula = sheets3.range("formula").cells(i,1).formula
         .ListColumns(i).DataBodyRange = .ListColumns(i).DataBodyRange.Value
      Next i
    End With
Debug.Print Timer - t
End Sub

回答1:


As an answer to my own question, What I was looking for is: " application.Evaluate " I am posting that so if anyone came here by search can find the idea and the sollution I eventually found. Here is an example:

Sheet3.ListObjects(1).ListColumns(3).DataBodyRange = [IFERROR(IF(COUNTIFS(ZZ84!$B:$B,[WO],ZZ84!$E:$E,"=*V99"‌​,ZZ84!$L:$L,"<>")=1,1,0),"")]

in this case there is no need to loop and for each range has to write needful line of code (Embed the function in VBA, what I excatly was looking for). The only different in above function with directly putting that in a excel cell is using [WO] instead of [@WO]. So evaluat caculate an array of data and directly write that in specified range. (here body range of list columns 3 ).

For me it helped to avoid crashes beacause of voilate calculation by my functions.

Another simple example would be:

range("b1:b10")=[if(row(1:10),if(a1:a10>3,"big","Small"))] 

or

range("b1:b10") = evaluate("if(row(1:10),if(" & range("a1:a10").address&">3,""big"",""small""))")

Kind regards, M



来源:https://stackoverflow.com/questions/46350498/how-to-write-results-of-a-formula-directly-into-an-excel-range-by-vba-code

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