我有这样的代码,其内容是:在没有公式的单元格中填充公式,然后复制/粘贴这些单元格的整行的值。我使用了2次"对于Next",首先用于填充公式,第二次用于粘贴值
Sub CDPSKoCongThuc()
Application.ScreenUpdating = False
Application.EnableEvents = False
Application.Calculation = xlCalculationManual
Dim RowNKC As Integer
RowNKC = Range("CuoiNKC").Row - 1
Dim RowCDPS As Integer
RowCDPS = Range("CuoiCDPS").Row - 1
Dim i As Integer
Dim x As Integer
For i = 9 To RowCDPS
If Cells(i, 9).HasFormula = False Then
Cells(i, 7).FormulaR1C1 = "=SUMIF(NKC!R9C12:R" & RowNKC & "C12,CDPS!RC[-6],NKC!R9C15:R" & RowNKC & "C15)"
Cells(i, 8).FormulaR1C1 = "=SUMIF(NKC!R9C13:R" & RowNKC & "C13,CDPS!RC[-7],NKC!R9C15:R" & RowNKC & "C15)"
Cells(i, 9).FormulaR1C1 = "=ROUND(SUMIF(NKC!R9C12:R" & RowNKC & "C12,CDPS!RC[-8],NKC!R9C14:R" & RowNKC & "C14),0)"
Cells(i, 10).FormulaR1C1 = "=ROUND(SUMIF(NKC!R9C13:R" & RowNKC & "C13,CDPS!RC[-9],NKC!R9C14:R" & RowNKC & "C14),0)"
Cells(i, 11).FormulaR1C1 = "=MAX(RC[-8]+RC[-4]-RC[-3]-RC[-7],0)"
Cells(i, 12).FormulaR1C1 = "=MAX(RC[-4]+RC[-8]-RC[-5]-RC[-9],0)"
Cells(i, 13).FormulaR1C1 = "=ROUND(MAX(RC[-8]+RC[-4]-RC[-7]-RC[-3],0),0)"
Cells(i, 14).FormulaR1C1 = "=ROUND(MAX(RC[-4]+RC[-8]-RC[-5]-RC[-9],0),0)"
End If
Next i
'Paste Values Formula
For x = 9 To RowCDPS
If Cells(x, 9).Font.Bold = False And Len(Cells(x, 1).Value) > 3 Then
Rows(x).EntireRow.Copy
Rows(x).PasteSpecial xlPasteValues
End If
Next x
Application.Calculation = xlCalculationAutomatic
Application.EnableEvents = True
Application.ScreenUpdating = True
End Sub
答案 0 :(得分:1)
我不打算全部写下来,但你可以使用VBA进行计算并将值放在单元格中,这样你就不必粘贴这些值或者完全使用excel计算。
例如......
Cells(i, 11).FormulaR1C1 = "=MAX(RC[-8]+RC[-4]-RC[-3]-RC[-7],0)"
将是
Cells(i, 11) = Application.Max(Cells(i, 3) + Cells(i, 7) - Cells(i,8) -Cells(i, 4), 0)
您还应该为每个工作表创建一个变量,并使用它们来引用单元格,以便更清晰地阅读
Dim shCDPS as Worksheet
Dim shNKC as worksheet
Set shCDPS = Sheets("CDPS")
Set shNKC = Sheets("NKC")
然后这个公式
Cells(i, 7).FormulaR1C1 = "=SUMIF(NKC!R9C12:R" & RowNKC & "C12,CDPS!RC[-6],NKC!R9C15:R" & RowNKC & "C15)"
会变成
shCDPS.Cells(i, 7) = Application.SumIf(shNKC.Range("L9:L" & RowNKC) , shCDPS.Range("A" & i), shNKC.Range("O15:O" & RowNKC))