在一段使用循环的代码中,我使用一个变量作为列跟踪器。当一些条件得到满足时,我想在一个特定的单元格中插入一个公式,用这个变量作为公式中提到的一个单元格的列。我创建了一个非常类似的代码,但变量 "m "是行跟踪器而不是列跟踪器,我成功地使用了以下一行。
If Cells(8, n).Value = "F" Then Cells(n, 4).Formula = "=AM4-sum(D10:D" & m & ")"
我想把这个 "m "作为一个列而不是一个行来使用 这里是一个不成功的尝试。
If Cells(8, n).Value = "F" Then Cells(11, n).Formula = "=AM4-SUM(Range(Cells(11, 7), Cells(11, " & m & ")))"
谁能帮我解决2d行的合成问题,使其工作?
先谢谢你了!
第1个子作为一个快速解决问题的方法。它可以成功地运行,如果值被分配给 m
和 n
. 你可以按原样运行第二和第三子。
Option Explicit
' A Quick Solution
Sub Quick()
Dim m As Long, n As Long
If Cells(8, n).Value = "F" Then
Cells(11, n).Formula = "=AM4-SUM(" _
& Range(Cells(11, 7), Cells(11, m)).Address(0, 0) _
& ")"
End If
End Sub
' The Versions
Sub Results()
Const EF1 As String = "=AM4-SUM("
Const EF3 As String = ")"
Dim m As Long, n As Long, EF2 As String
n = 1
m = 10 ' At least 10 (Note the different results for 10).
'If Cells(8, n).Value = "F" Then Cells(n, 4).Formula = _
"=AM4-SUM(D10:D" & m & ")"
' Old String Version (You can replace "D" with 4.)
If Cells(8, n).Value = "F" Then
EF2 = "D10:D" & m
Cells(n, "D").Formula = EF1 & EF2 & EF3
End If
Debug.Print "D10:D" & m
' Old Range Version (You can replace "D" with 4.)
If Cells(8, n).Value = "F" Then
EF2 = Range(Cells(10, "D"), Cells(m, "D")).Address(0, 0)
Cells(n, "D").Formula = EF1 & EF2 & EF3
End If
Debug.Print Range(Cells(10, "D"), Cells(m, "D")).Address(0, 0)
'If Cells(8, n).Value = "F" Then Cells(11, n).Formula = _
"=AM4-SUM(Range(Cells(11, 7), Cells(11, " & m & ")))"
m = 7 ' At least 7.
' New Range Version (You can replace "G" with 7.)
If Cells(8, n).Value = "F" Then
EF2 = Range(Cells(11, "G"), Cells(11, m)).Address(0, 0)
Cells(11, n).Formula = EF1 & EF2 & EF3
End If
Debug.Print Range(Cells(11, "G"), Cells(11, m)).Address(0, 0)
End Sub
' A Possible Scenario (Old Range Version)
Sub monitorOldRange()
Const sumFR As Long = 10 ' Sum First Row Number
Const sumLRStart As Long = 11 ' Sum Starting Last Row Number
Const sumCol As Long = 4 ' Sum Column Number
Const srcFC As Long = 1 ' Source First Column Number
Const srcLC As Long = 5 ' Source Last Column Number
Const srcRow As Variant = 8 ' Source Criteria Row Number
Const Criteria As String = "F" ' Source Criteria String
Const tgtCol As Long = 4 ' Target Column Number
Dim scc As Long ' Source Column Counter
Dim sumLR As Long ' Sum Last Row Counter
Dim EF As String ' Excel Formula
Debug.Print String(50, "-") & vbCr & "Old Range Version:"
sumLR = sumLRStart
For scc = srcFC To srcLC
' EF = "=AM64-SUM(D10:D" _
' & fcc _
' & ")"
EF = "=AM64-SUM(" _
& Range(Cells(sumFR, sumCol), Cells(sumLR, sumCol)).Address(0, 0) _
& ")"
Debug.Print Cells(srcRow, scc).Address, Cells(scc, tgtCol).Address, EF
' If Cells(srcRow, scc).Value = Criteria Then
' Cells(scc, tgtCol).Formula = EF
' End If
sumLR = sumLR + 1
Next scc
End Sub