简体   繁体   中英

VBA insert a formula to existing cell

Cell A1 refers to Cell A5, which has a value of 5.5. I want to insert say a round function to Cell A1 that reads =round(A5,). I tried the following code below but it's not working as I intend it to.

Sub roundmacro()
   Dim n As String
   n = Range("A1").Value 'returns the value but I need reference from that range object instead  
   Range("A1").Formula = "=round(" & n & ",)"
End Sub

Thanks in advance

Range("A1").Formula = "=Round(" & Mid(Range("A1").Formula, 2) & ",)"

This turns any existing formula into a rounding of that formula. So if the initial formula was =A5 , the new formula becomes =Round(A5,) .

ps Works for any initial formula that returns a number (you cannot round a string, naturally).

那么你想让A1中的公式显示“A5”吗?

Range("A1") = "=Round(A5,)"

Wouldn't it be better to do the calculation in VBA, like this:

Sub formulas()

Range("A1").Value = Application.WorksheetFunction.Round(Range("A5").Value, 0) ' You can put any formula after the 'Application.WorksheetFunction.'

End Sub

Works fine for me, A1 = 6

Sub roundmacro()
   Dim n As String
   n = Range("A5").Value
   Range("A1").Formula = "=round(" & n & ",)"
End Sub

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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