在下面的代码行中,我试图对变量范围求和(列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
答案 0 :(得分:2)
您的工作表名称(rng.Value
)是否包含空格?如果是这样,您需要在名称周围添加单引号,如下所示:
='Test Sheet'!A:A
此外,您使用的是R1C1表示法,它与A1表示法(see more info here)略有不同。以下两个示例都应该有效。
使用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
函数的一个额外注释...
如果你正在查看大量的列,这可能会很难写出来,所以我有一个函数可以用来更简单地获取这个值(完全公开,我从{抓住了这个) {3}},但我自己更新了2007/2010/2013版本的Excel ):
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 A-Z
ColumnLetter = Chr(ColumnNumber + 64)
End If
End Function
您可以使用Choose
。
sSumColumn = ColumnLetter(Lsumcolumn)
公式