VBAmacros与公式显示(Excel)
我有一个代码在我的macros返回我在我的单元格(A5)结果像#name
?
Range("A5").Select ActiveCell.FormulaR1C1 = "=Application.Sum(Range(Cells(1, 5), Cells(20, 5)))" End Sub
#name?
在我的VB代码中包含引号之间的文本公式
=Application.Sum(Range(Cells(1, 5), Cells(20, 5)))
如果我不写引号就会返回一个结果 。(范围总和)
ActiveCell.FormulaR1C1 = Application.Sum(Range(Cells(1, 5), Cells(20, 5)))
但我需要在我的单元格A5结果和公式,我怎么得到这个结果。 也许这足以改变一些select?
由于您想使用VBA代码在单元格A5中input公式,因此您需要使用正确的参数:
Range(Cells(1, 5), Cells(20, 5))
R1C5:R20C5
Range(Cells(1, 5), Cells(20, 5))
是VBA,如果您想将其作为Excel工作表单元格识别的公式,则需要使用R1C5:R20C5
。
另外,而不是Application.Sum
只使用Sum
。
你应该避免使用Select
和ActiveCell
,直接使用Range("A5").FormulaR1C1
所以只需使用下面的行代码:
Range("A5").FormulaR1C1 = "=Sum(R1C5:R20C5)"
我发现使用一个公式来添加公式更简单
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
它所做的只是将公式input单元格A5
如果你想在你的单元格中有一个公式指向你在VBA代码中定义的某个范围,那么你可以使用
Range("A5").FormulaR1C1 = "=Sum(" & Range(Cells(1, 5), Cells(20, 5)).Address(, , xlR1C1) & ")"
如果我理解正确,你想在A5
显示公式和结果 。 如果是这样,请使用
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)
这个代码可能会得到改善(使用Sum
而不是Application.Sum
,例如)