简体   繁体   中英

Alter cell value based on relative cell reference

I would like to create a macro which looks where there are "0" in the column and:

  • it replaces the "0" with half the value of the cell above
  • it replaces the value of the cell above with its half

I tried to record something like:

Sub Macro14()
' Macro14 Macro
'
ActiveCell.FormulaR1C1 = "=R[-1]C/2"
Range("N57").Select
Selection.Copy
Selection.PasteSpecial Paste:=xlPasteValuesAndNumberFormats, Operation:= _
    xlNone, SkipBlanks:=False, Transpose:=False
Range("N56").Select
Application.CutCopyMode = False
Selection.ClearContents
Range("N57").Select
Selection.Copy
Range("N56").Select
ActiveSheet.Paste
ActiveSheet.Paste
Application.CutCopyMode = False
End Sub

But I don't know how to refer to the cells which contain "0" in a given column.

Your question is a bit unclear but this may help you.

Sub Ncolumn()
   For Each Rng In Range("N1:N60") ' Change range to suit
       If Rng.Value = "0" Then Rng.Value = Cells(Rng.Row - 1, Rng.Column).Value / 2
   Next Rng
End Sub

You'll want to loop through your column, and add conditional logic. use this to help you along the way.

 dim rNg as range
 dim rCell as range
 set rNg = ThisWorkbook.Sheets("YourSheet").Range("Your Range")
 for each rCell in rNg.Cells
 if rCell.Value = 0 Then
      'your code
 end if
 next rCell

this is only to get your started. the best way to learn it to figure a few things out by trial and error. this is however for the most part what you need.

Also copy and pasting like you do in your example above is awfully taxing. You should get used to telling cells what there values are. ie

ThisWookbook.Sheets("Sheet1").Range("A1").Value = ThisWorkbook.Sheets("Sheet2").Range("A1").Value

You are new so this nuance wont be too relevant but when you get into larger scripts for vba performance will be a signifcant issue then.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM