VBA公式-每行数据调整

时间:2019-01-30 17:47:40

标签: excel vba excel-formula

 Sub Sample()

     Dim lastRow As Long, i As Long
     Dim ws As Worksheet

     Set ws = Sheets("Storage NSNR")

     lastRow = ws.Range("K" & Rows.Count).End(xlUp).Row

     With ws
         For i = 1 To lastRow
             If Len(Trim(.Range("K" & i).Value)) <> 0 Then _
             .Range("L" & i).Formula = "=(NETWORKDAYS(J2, K2)-1)*($P$1-$O$1)+IF(NETWORKDAYS(K2,K2),MEDIAN(MOD(K2,1), $P$1,
 $O$1),$P$1)-MEDIAN(NETWORKDAYS(J2,J2)*MOD(J2,1), $P$1, $O$1)"
         Next i
     End With

 End Sub

嗨,

有人可以帮助我调整公式吗

=(NETWORKDAYS(J2, K2)-1)*($P$1-$O$1)+IF(NETWORKDAYS(K2,K2),MEDIAN(MOD(K2,1), $P$1, $O$1),$P$1)-MEDIAN(NETWORKDAYS(J2,J2)*MOD(J2,1), $P$1, $O$1)

我希望自动将“ J2”和“ K2”调整为“ J3”和“ K3”,依此类推,类似于向下拖动公式。我到处都看过,但似乎找不到正确的应用方法。

基本上,该公式从下一列“ L1”开始,直到最后一个可用于“ K”的条目。

任何帮助将不胜感激。谢谢。

1 个答案:

答案 0 :(得分:1)

更改为xlR1C1样式公式并使用.Range("L" & i).FormulaR1C1 = ...

.Range("L" & i).Formular1c1 = "=(NETWORKDAYS(rc10, rc11)-1)*(r1c16-r1c15)+IF(NETWORKDAYS(rc11, rc11), MEDIAN(MOD(rc11, 1), r1c16, r1c15), r1c16)-MEDIAN(NETWORKDAYS(rc10, rc10)*MOD(rc10,1), r1c16, r1c15)"

如果您不太熟悉xlR1C1语法,请让VBA完成。

 Sub Sample()

     Dim i As Long, fA1 As String, fR1C1 As String

     fA1 = "=(NETWORKDAYS(J2, K2)-1)*($P$1-$O$1)+IF(NETWORKDAYS(K2,K2),MEDIAN(MOD(K2,1), $P$1, $O$1),$P$1)-MEDIAN(NETWORKDAYS(J2,J2)*MOD(J2,1), $P$1, $O$1)"
     fR1C1 = Application.ConvertFormula(Formula:=fA1, _
                                        FromReferenceStyle:=xlA1, _
                                        ToReferenceStyle:=xlR1C1, _
                                        RelativeTo:=Range("L2"))

     Debug.Print fR1C1
     '=(NETWORKDAYS(RC[-2], RC[-1])-1)*(R1C16-R1C15)+IF(NETWORKDAYS(RC[-1],RC[-1]),MEDIAN(MOD(RC[-1],1), R1C16, R1C15),R1C16)-MEDIAN(NETWORKDAYS(RC[-2],RC[-2])*MOD(RC[-2],1), R1C16, R1C15)

     With Worksheets("Storage NSNR")
         With .Range(.Cells(2, "K"), .Cells(Rows.Count, "K").End(xlUp))
            .SpecialCells(xlCellTypeConstants, xlNumbers).Offset(0, 1).FormulaR1C1 = fR1C1
         End With
     End With

 End Sub