使用下面的代码我尝试循环列和行。当绿色单元格导入公式字符串中的范围时。在第 7 行,我想导入一个对绿色单元格求和的公式,但我希望显示该公式。循环工作正常,公式创建正常,但作为字符串而不是公式导入。
任何帮助将不胜感激。
Sub test()
Dim Row As Long
Dim Col As Long
Dim strFormula As String
With ThisWorkbook.Worksheets("Sheet1")
'Loop columns
For Col = 1 To 3
'Clear strFormula variable
strFormula = ""
'Loop rows
For Row = 1 To 5
'Check if cell is green
If .Cells(Row, Col).Interior.Color = 9359529 Then
'Create formula
If strFormula = "" Then
strFormula = """=SUM(.cells(" & Row & "," & Col & ")"
Else
strFormula = strFormula & ",.cells(" & Row & "," & Col & ")"
End If
Else
End If
Next Row
'Finalize formula
If strFormula <> "" Then
strFormula = strFormula & ")"""
'Import formula
.Cells(7, Col).Formula = strFormula
Else
End If
Next Col
End With
End Sub
这不是 Excel 公式的正确语法。你可以使用这样的东西:
Sub test()
Dim Row As Long
Dim Col As Long
Dim strFormula As String
With ThisWorkbook.Worksheets(1) ' "Sheet1"
'Loop columns
For Col = 1 To 3 Step 2
'Clear strFormula variable
strFormula = ""
'Loop rows
For Row = 1 To 5
'Check if cell is green
If .Cells(Row, Col).Interior.Color = 9359529 Then
'Create formula
If strFormula = "" Then
strFormula = "=SUM(R" & Row & "C" & Col
Else
strFormula = strFormula & ",R" & Row & "C" & Col
End If
End If
Next Row
'Finalize formula
If strFormula <> "" Then
strFormula = strFormula & ")"
'Import formula
.Cells(7, Col).FormulaR1C1 = strFormula
Else
End If
Next Col
End With
End Sub