2014-09-04 124 views
4

我試圖填補C列的公式是這樣的:VBA:跳躍單元範圍內

LastRow = Range("A65536").End(xlUp).Row 
Range(Cells(1, 3), Cells(LastRow, 3)).Formula = "=A1*B1" 

,它工作正常。但是,是否可以跳過列C中的那些單元格,該值例如> 0?

A B C -> A B C 
3 2 0 3 2 6 
3 4 0 3 4 12 
5 6 5 5 6 5 <- this value is not updated 
+1

@Mehow:有可能:) – 2014-09-04 08:39:46

+1

@SiddharthRout ++你的答案,我把我的最後一點回來:) – 2014-09-04 08:47:26

回答

1

一種方式做到這一點通過循環:

Sub test() 

      Dim rngTest As Range 
      Dim rngCell As Range 

      LastRow = Range("A65536").End(xlUp).Row 
      Set rngTest = Range(Cells(1, 3), Cells(LastRow, 3)) 
      Application.Calculation = xlCalculationManual 
      For Each rngCell In rngTest.Cells 
       If Not rngCell <> "" Then 
        rngCell.Formula = "=" & rngCell.Offset(, -2).Address & "*" & rngCell.Offset(, -1).Address 
       End If 
      Next 
      Application.Calculation = xlCalculationAutomatic 
    End Sub 
+0

謝謝,您的解決方案對我來說更容易理解。它工作正常! – gaffcz 2014-09-04 10:54:43

6

爲此,您將不得不稍微改變您的數據外觀。例如,您需要將「標題」添加到第一行。我們會這麼做的原因是因爲我們將使用AutoFilter

比方說,你的數據看起來像這樣

enter image description here

現在使用此代碼

Sub Sample() 
    Dim ws As Worksheet 
    Dim copyFrom As Range 
    Dim lRow As Long 

    '~~> Change this to the relevant sheet 
    Set ws = ThisWorkbook.Worksheets("Sheet1") 

    With ws 

     '~~> Remove any filters 
     .AutoFilterMode = False 

     '~~> Get lastrow in column c 
     lRow = .Range("C" & .Rows.Count).End(xlUp).Row 

     '~~> Filter the col C to get values which have 0 
     With .Range("C1:C" & lRow) 
      .AutoFilter Field:=1, Criteria1:="=0" 

      Set copyFrom = .Offset(1, 0).SpecialCells(xlCellTypeVisible) 

      '~~> Assign the formula to all the cells in one go 
      If Not copyFrom Is Nothing Then _ 
      copyFrom.Formula = "=A" & copyFrom.Row & "*B" & copyFrom.Row 
     End With 

     '~~> Remove any filters 
     .AutoFilterMode = False 
    End With 
End Sub 

輸出

enter image description here

+0

非常感謝你! :-) – gaffcz 2014-09-04 10:52:08