总和variables列
在下面的代码行我试图总结一个variables范围(列U)。 你能让我知道我在做什么我的代码错误(任何帮助表示赞赏):
有问题的代码行:
Sheets(gcsReportSheetName).Cells(LCounter, 3).FormulaR1C1 = "=sum(" & rng.Value & "!" & Lsumcolumn & ":" & Lsumcolumn & ")"
完整的代码。
Sub Report() Dim rng As Range Dim LCounter As Long Dim sLsheet As String Dim Lsumcolumn As Long Set gRwksconfigeration = Sheets("Config") Set gRnct_Funds_2 = gRwksconfigeration.Range(CT_Funds_2) LCounter = 3 For Each rng In gRnct_Funds_2 Sheets(gcsReportSheetName).Cells(LCounter, 1) = rng.Value If rng.Value = "" Then Exit Sub Else Sheets(gcsReportSheetName).Cells(LCounter, 2) = Sheets(rng.Value).Cells.Find(What:="Value", After:=Cells(1, 1), LookIn:=xlValues, LookAt:= _ xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:= _ False, SearchFormat:=False).End(xlDown).Value Lsumcolumn = Sheets(rng.Value).Cells.Find(What:="illiquid check", After:=Cells(1, 1), LookIn:=xlValues, LookAt:= _ xlWhole, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:= _ False, SearchFormat:=False).Column Sheets(gcsReportSheetName).Cells(LCounter, 3).FormulaR1C1 = "=sum(" & rng.Value & "!" & Lsumcolumn & ":" & Lsumcolumn & ")" LCounter = LCounter + 1 End If Next End Sub
你的表名( rng.Value
)是否包含空格? 如果是这样,您需要在名称周围添加单引号,如下所示:
='Test Sheet'!A:A
此外,您正在使用R1C1表示法,它与A1表示法有点不同( 请参阅此处的更多信息 )。 以下两个例子都应该可以工作。
你用R1C1表示法的代码应该是这样的:
Sheets(gcsReportSheetName).Cells(LCounter, 3).FormulaR1C1 = "=sum('" & rng.Value & "'!C" & Lsumcolumn & ")"
你用A1符号的代码应该是这样的:
sSumColumn = Choose(Lsumcolumn,"A","B","C","D","E","F","G") ' Expand this to include all column headers. Sheets(gcsReportSheetName).Cells(LCounter, 3).Formula = "=sum('" & rng.Value & "'!" & sSumColumn & ":" & sSumColumn & ")"
即使您的工作表名称不包含空格,该语法仍然可以工作。
关于Choose
函数来获取列标题的一个额外注意事项…
如果你正在查看大量的列,这可能是一个痛苦,所以我有一个function,我用它来更简单地获取这个值( 完全公开,我从互联网上的另一个网站抓住这个,但自己更新了Excel的2007/2010/2013版本 ):
Public Function ColumnLetter(ColumnNumber As Integer) As String If ColumnNumber > 26 Then If ColumnNumber > 702 Then ' Compatible with Excel 2007+ extension of columns ColumnLetter = Chr(Int((Int((ColumnNumber - 1) / 26) - 1) / 26) + 64) & _ Chr((Int((ColumnNumber - 1) / 26) - 1) Mod 26 + 65) & _ Chr(((ColumnNumber - 1) Mod 26) + 65) Else ' 1st character: Subtract 1 to map the characters to 0-25, ' but you don't have to remap back to 1-26 ' after the 'Int' operation since columns ' 1-26 have no prefix letter ' 2nd character: Subtract 1 to map the characters to 0-25, ' but then must remap back to 1-26 after ' the 'Mod' operation by adding 1 back in ' (included in the '65') ColumnLetter = Chr(Int((ColumnNumber - 1) / 26) + 64) & _ Chr(((ColumnNumber - 1) Mod 26) + 65) End If Else ' Columns AZ ColumnLetter = Chr(ColumnNumber + 64) End If End Function
而不是上面的Choose
公式,可以使用sSumColumn = ColumnLetter(Lsumcolumn)
。