从所选值中插入行

时间:2015-03-04 08:59:34

标签: excel vba excel-vba

我有2列A和B.

A = 12 (months)
B = 12.000.000
C (result) = B/A = 12.000.000 / 12 = 1.000.000

我想要的结果是循环自动根据月份(A)插入新行

month     amount
1        1.000.000
2        1.000.000
3        1.000.000
4        1.000.000
5        1.000.000
6        1.000.000
.
.
.
12       1.000.000

这是我的完整代码,同时在我的案例中添加:

Private Sub cmdAdd_Click()
Dim lRow As Long
Dim lPart As Long
Dim ws As Worksheet
Set ws = Worksheets("PostBudgetData")

lRow = ws.Cells.Find(What:="*", SearchOrder:=xlRows, _
    SearchDirection:=xlPrevious, LookIn:=xlValues).Row + 1

lPart = Me.cboMonth.ListIndex
    If CheckBox1.Value = True Then
    If Trim(Me.cboMonth.Value) = "" Then
        Me.cboMonth.SetFocus
        MsgBox "Please enter a part number"
    Exit Sub
    End If
End If



'copy the data to the database
With ws
  .Cells(lRow, 1).Value = Me.cboYear.Value
If CheckBox1.Value = True Then
      .Cells(lRow, 2).Value = Me.cboMonth.List(lPart, 0)
End If
  .Cells(lRow, 3).Value = Me.cboBrand.Value
  .Cells(lRow, 4).Value = Me.cboPostBudget.Value
  .Cells(lRow, 5).Value = Me.cboArea.Value
  .Cells(lRow, 6).Value = Me.txtValue.Value
  .Cells(lRow, 7).Value = Me.cboSBU.Value
End With

'clear the data
Me.cboMonth.Value = ""
Me.cboYear.Value = ""
Me.cboBrand.Value = ""
Me.cboPostBudget.Value = ""
Me.cboArea.Value = ""
Me.cboSBU.Value = ""

'Me.txtValue.Value = Format(Date, "Medium Date")
Me.txtValue.Value = 0

If CheckBox1.Value = True Then
      Me.cboMonth.SetFocus
End If

End Sub

但它不是循环的。我不知道在插入新行时循环使用vba,因为它只插入1行。这就是我尝试的不只是我累了,没有做任何事情就要求。

2 个答案:

答案 0 :(得分:0)

此VBA代码从单元格A2B2获取值,并在列DE上生成新行:

Private Sub Worksheet_Change(ByVal Target As Range)
    first_column = 4 'first column of results
    total_months = Cells(2, 1) 'cell of total months
    total_amount = Cells(2, 2) 'cell of total amount
    calculated_value = total_amount / total_months
    changed = False
    Dim a As Range
    Select Case Target.Address
        Case "$A$2"
            changed = True
        Case "$B$2"
            changed = True
    End Select
    If changed = True Then 'only updates if change cells A2 or B2
        Columns(first_column).ClearContents
        Columns(first_column + 1).ClearContents
        Cells(1, first_column) = "month"
        Cells(1, first_column + 1) = "amount"
        For i = 2 To total_months + 1 ' loop the number of rows=totalmonths
            Cells(i, first_column) = i - 1
            Cells(i, first_column + 1) = calculated_value
        Next i
    End If
End Sub

您必须复制代码,转到View - > Excel中的宏,创建一个新的(任何名称都有效),在左栏中双击要使用它的工作表(图中的红色标记),在右侧粘贴代码。

VBA Macro on Sheet

这就是它的样子:

excel_rows

答案 1 :(得分:0)

如果您正在寻找的是如何在vba中循环,那么这可能对您有所帮助:

'12 = times you want to loop
For i = 1 to 12 

'inserts row before row number i
ThisWorkbook.Sheets(1).Rows(i).Insert
'fill cells with content
Sheets(1).Cells(i,1) = <something

'loop 
Next i