我正在使用Excel编写报表,实际上是在VB6中构建它以在excel中生成。从下图中可以看出,我有两列,BOUGHT和SOLD。我要做的是取两者的TOTALS并将它们放在TOTAL行中。
所以我尝试使用这样的代码,基本上首先指定我想要放置值的位置
xlrow= 14
xlCol=2
ActiveCell(xlRow, xlCol) = (ActiveCell.FormulaR1C1 = "=sum(B6:B12)")
'我尝试了这个,但它给了我一个值FALSE,不确定如何去做 基本上我想进入BOUGHT总细胞,取A,B,C,D,其他,无,未知的总和并让它走到下一个细胞并且总共出售:
将它放在一个循环中,以便它一直到记录计数结束(见下文)
我使用记录集填充excel标题(包等),因为我正在尝试将其设置为动态(仅执行我拥有的多个列的总数并在结束时停止)。所以这就是我正在努力建立的
xlrow=14
xlcol=2
rCount=(g_RS.recordcount *2) 'because I have two columns (Bought,sold) for each Heading
dim i as integer
for i = 1 to rCount -1
ActiveCell(xlRow, xlCol) = (ActiveCell.FormulaR1C1 = "=sum(B6:B12)")
xlcol=xlcol+1
next
答案 0 :(得分:1)
为了帮助您更好地了解如何对此进行编码,以下是一个示例。您可以通过其余代码扩展它,但我相信它适用于您的情况。
您当然可以使用R1C1表示法来构建公式,但您必须正确包含所有部件才能创建正确的引用。如果需要,请在字符串上使用Debug.Print
来查看它的外观。
添加了边框格式
Option Explicit
Sub GenerateTotals()
Dim ws As Worksheet
Dim dataRowStart As Long
Dim dataRowEnd As Long
Dim totalsRow As Long
Dim dataColumnStart As Long
Dim columnCount As Long
Dim dataRangeR1C1 As String
Dim i As Long
'--- set these values specifically, or you can calculate them
Set ws = ActiveSheet
dataRowStart = 6
dataRowEnd = 12
totalsRow = 14
dataColumnStart = 2
columnCount = 2
'countCount = (g_RS.RecordCount * 2)
For i = dataColumnStart To (dataColumnStart + columnCount - 1)
dataRangeR1C1 = "R" & dataRowStart & "C" & i & ":R" & dataRowEnd & "C" & i
With ws.Cells(totalsRow, i)
.FormulaR1C1 = "=SUM(" & dataRangeR1C1 & ")"
.Borders(xlEdgeTop).LineStyle = xlContinuous
.Borders(xlEdgeTop).ColorIndex = xlAutomatic
.Borders(xlEdgeTop).TintAndShade = 0
.Borders(xlEdgeTop).Weight = xlThin
.Borders(xlEdgeBottom).LineStyle = xlContinuous
.Borders(xlEdgeBottom).ColorIndex = xlAutomatic
.Borders(xlEdgeBottom).TintAndShade = 0
.Borders(xlEdgeBottom).Weight = xlThick
End With
Next i
Set ws = Nothing
End Sub