Excel报表 – 公式VBA

对于我在VB6中构build的报告,我遇到了一些困难。 Bascially我正在build立一个dynamic报告的标题和2列(客户,学生)从logging集填充。 正如您在图片中看到的,在我的标题末尾,我添加了一个TOTAL标题,下面有客户和学生。 我试图把每个栏目中的所有客户总计在一起,总计为总计,与学生一样。 列(UCLA,SDU,SCCU)的数量可能会有所不同,所以我试图使它dynamic。基本上从A开始,然后是B,然后是C,D和NONE。 有任何想法吗? 在这里输入图像说明 编辑:我从SQL SERVER中select短标签,并填充,直到g_RS3为空

Do While Not g_RS3.EOF With xlSheet.Cells(xlRow, xlCol) .Value = g_RS3("ShortLabel") .Offset(1, 0).Value = " Clients " .Offset(1, 1).Value = " Students" With .Offset(1, 0) .Font.Bold = True .Borders.Weight = xlThin End With With .Offset(1, 1) .Font.Bold = True .Borders.Weight = xlThin End With With .Resize(1, 2) .Font.Bold = True .WrapText = True .VerticalAlignment = xlCenter .Merge .HorizontalAlignment = xlCenter .Borders.Weight = xlThin End With End With xlCol = xlCol + 2 g_RS3.MoveNext Loop With xlSheet.Cells(xlRow, xlCol) .Value = "TOTAL" .Offset(1, 0).Value = "Clients" .Offset(1, 1).Value = "Students" With .Offset(1, 0) .Font.Bold = True .Borders.Weight = xlThin End With With .Offset(1, 1) .Font.Bold = True .Borders.Weight = xlThin End With With .Resize(1, 2) .Font.Bold = True .WrapText = True .VerticalAlignment = xlCenter .Merge .HorizontalAlignment = xlCenter .Borders.Weight = xlThin End With End With 

然后,我从xlrow = 4 xlcol = 2开始,用数据填充CLIENT AND STUDENT列。 我有的循环是相当长的。 但用户只能查看摘录。 一旦它的产生取决于他们,他们如何处理。 应用程序给他们一个添加SHORTLABEL的选项,一旦生成它,需要在提取中显示。

SUMIF函数或SUMIFS函数都可以轻松执行此操作。

在H4中作为标准配方,

 =sumifs($b4:$g4, $b$3:$g$3, h$3) 

填写正确和下降。

在VBA中,

 with worksheets("Sheet1") .range("H4:I8").formula = "=sumifs($b4:$g4, $b$3:$g$3, h$3)" 'optional revert to values only '.range("H4:I8") = .range("H4:I8").values end with 

你将不得不确定客户/学生范围的范围,但是只有一半是知道把公式放在哪里(如H4)。

VBA

我已经删除了很多原来的代码使用的冗余。 鉴于您还没有将数据填充到客户端/学生列中,我使用了一种方法,其中Total列总是写入正确的公式。 如果还有另一个行集合,那么总计将被覆盖,并在右侧创build一个新的行。

 Dim xlStartCol As Long xlStartCol = xlCol Do While Not g_RS3.EOF With xlSheet.Cells(xlRow, xlCol) .Resize(1, 2).Merge .Value = "TEST" 'g_RS3("ShortLabel") .Offset(1, 0).Resize(1, 2) = Array("Clients", "Students") .Offset(2, 0).Resize(1, 2).ClearContents With .Offset(0, 1) .Resize(1, 2).Merge .Value = "Total" 'keep writing Total to the right; it will be overwritten if there is another ShortLabel .Offset(1, 0).Resize(1, 2) = Array("Clients", "Students") .Offset(2, 0).Resize(1, 2).Formula = _ "=SUMIFS(" & Range(.Parent.Cells(xlRow + 2, xlStartCol), .Parent.Cells(xlRow + 2, xlCol + 1)).Address(0, 1) & Chr(44) & _ Range(.Parent.Cells(xlRow + 1, xlStartCol), .Parent.Cells(xlRow + 1, xlCol + 1)).Address(1, 1) & Chr(44) & _ .Parent.Cells(xlRow + 1, xlCol - 1).Address(1, 0) & Chr(41) End With With .Resize(2, 4) .Font.Bold = True .VerticalAlignment = xlCenter .HorizontalAlignment = xlCenter .Borders.Weight = xlThin End With End With xlCol = xlCol + 2 g_RS3.MoveNext Loop 

一旦实际上将数据填充到每对列并知道范围,只需使用Range.FillDown方法来填充其余公式。

xlCol

我build议删除不相关的部分logging的代码。 logging的代码非常冗长,妨碍了可读性。 您可能还想查看在T-SQL中创build查询的For XML方法。 这将扩展返回的列,并允许您使用字段计数来确定范围。