问题
I want to copy the amount and paste it to all empty cells above the amount as shown in the picture , using VBA or Macro in MS Excel
Edit: This is what I done it.
Sub Macro2()
Range("F5").Select
Selection.Copy
Range("F2:F4").Select
ActiveSheet.Paste
Range("F7").Select
Application.CutCopyMode = False
Selection.Copy
Range("F6").Select
ActiveSheet.Paste
Range("F12").Select
Application.CutCopyMode = False
Selection.Copy
Range("F8:F11").Select
ActiveSheet.Paste
End Sub
This code only works on this table only. If contents change it's not working. eg: if more items added, it's giving different outputs.
Can anyone help me to resolve it. Thanks in advance.
回答1:
As far as the logic of the copying of values, I think this is something you need to work out. But I do have some hints of how to get there.
Do NOT use Select/Copy/Paste - Use direct assignment instead
Range("G5").Resize(3, 1).Value = Range("F5").Value
This will take the one value in cell F5
and use it to assign the three cells G5:G7
.
To pick a specific value in a table, use the .Cells()
function
For i=1 to 10
Range("B2").Cells(i,1).Value = Range("A2").Cells(i,1).Value
Next i
To count the number of rows down, or column across that have values use the following functions (placed in a module).
Public Function CountCols(ByVal r As Range) As Long
If IsEmpty(r) Then
CountCols = 0
ElseIf IsEmpty(r.Offset(0, 1)) Then
CountCols = 1
Else
CountCols = r.Worksheet.Range(r, r.End(xlToRight)).Columns.Count
End If
End Function
Public Function CountRows(ByVal r As Range) As Long
If IsEmpty(r) Then
CountRows = 0
ElseIf IsEmpty(r.Offset(1, 0)) Then
CountRows = 1
Else
CountRows = r.Worksheet.Range(r, r.End(xlDown)).Rows.Count
End If
End Function
To be used as
Dim n as Long
' Count rows in table starting from A2
n = CountRows(Range("A2"))
Dim r as Range
' Set a range reference to n×1 cells under A2
Set r = Range("A2").Resize(n,1)
To check if a cell is empty, use IsEmpty()
just like I have used in CountRows()
.
Can you piece all these pieces together to make a macro that does what you want? You should: a) check how many rows are in the table, b) go down the cells and check if they are empty in the destination and c) if they are, copy from the same row in the source.
来源:https://stackoverflow.com/questions/47516244/how-to-copy-a-cell-paste-it-to-multiple-cells-in-excel-vba-macro