[英]VBA macro with formula showing (Excel)
I have a code in my macro that return me in my Cell(A5) result like #name
? 我的宏中有一个代码,可以将我的Cell(A5)结果返回给我,例如#name
?
Range("A5").Select
ActiveCell.FormulaR1C1 = "=Application.Sum(Range(Cells(1, 5), Cells(20, 5)))"
End Sub
#name?
include a formula of text between quotation marks in my VB code 在我的VB代码中的引号之间包含一个文本公式
=Application.Sum(Range(Cells(1, 5), Cells(20, 5)))
If i will write without quotation marks it will returns me a result .(sum of range) 如果我写不带引号,它将返回一个结果 。(范围之和)
ActiveCell.FormulaR1C1 = Application.Sum(Range(Cells(1, 5), Cells(20, 5)))
but I need to have in my cell A5 result and formula, how i got this result. 但是我需要在单元格A5的结果和公式中包含如何获得此结果的信息。 Maybe it's enough to change some options? 也许更改某些选项就足够了吗?
Since you want to use a VBA code to enter a formula in Cell A5, then you need to use the right parameters: 由于您要使用VBA代码在单元格A5中输入公式,因此您需要使用正确的参数:
Range(Cells(1, 5), Cells(20, 5))
is VBA, if you want it as a formula that an Excel sheet's cell recognizes, you need to use R1C5:R20C5
. Range(Cells(1, 5), Cells(20, 5))
R1C5:R20C5
Range(Cells(1, 5), Cells(20, 5))
是VBA,如果要将其用作Excel工作表单元格可以识别的公式,则需要使用R1C5:R20C5
。
Also, instead of Application.Sum
just use Sum
. 另外,代替Application.Sum
只需使用Sum
。
You should try avoid using Select
and ActiveCell
and directly use Range("A5").FormulaR1C1
您应该避免使用Select
和ActiveCell
而直接使用Range("A5").FormulaR1C1
So just use the line code below: 因此,只需使用以下代码:
Range("A5").FormulaR1C1 = "=Sum(R1C5:R20C5)"
I found it simpler to add a formula to the cell using 我发现使用以下方法向单元格添加公式更简单
Sub addFormula()
Dim ws As Worksheet
Set ws = Worksheets("Sheet1")
With ws
.Range("A5").NumberFormat = "General" 'This formats A5 as general
.Range("A5").Formula = "=SUM(F1:F20)"
End With
End Sub
All it does is enters the formula into the cell A5 它所做的就是将公式输入到单元格A5中
如果您想在单元格中使用一个公式,该公式指向您在VBA代码中定义的某个范围,则可以使用
Range("A5").FormulaR1C1 = "=Sum(" & Range(Cells(1, 5), Cells(20, 5)).Address(, , xlR1C1) & ")"
If I understood correctly, you want to show in A5
both the formula and the result . 如果我理解正确,则希望在A5
同时显示公式和结果 。 If so, use 如果是这样,请使用
Dim aux As Variant
aux = Application.Sum(Range(Cells(1, 5), Cells(20, 5)))
ActiveCell.Value = "Application.Sum(Range(Cells(1, 5), Cells(20, 5))) : " & CStr(aux)
This code caould likely be improved (using Sum
instead of Application.Sum
, eg) 该代码可能会得到改进(例如,使用Sum
代替Application.Sum
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.