简体   繁体   English

如何根据VBA中的条件添加行?

[英]How to add rows based on a condition in VBA?

I have a spreadsheet that looks like this:我有一个看起来像这样的电子表格:

(C5): Top
(C6):
(C7):
(C8):
(C9):
(C10):
(C11):
(C12):
(C13):
(C14): Bottom

There are 2 user defined variables, apple and orange.有 2 个用户定义的变量,apple 和 orange。 Say that apple=3 and orange=3.假设 apple=3 和 orange=3。 The output should look like this:输出应如下所示:

(C5): Top
(C6): Apple 1
(C7): Apple 2
(C8): Apple 3
(C9): Orange 1
(C10): Orange 2
(C11): Orange 3
(C12): Hello world 1
(C13): Hello world 2
(C14): Bottom

If apple = 3 and orange = 4, I want the output to look like this:如果 apple = 3 和 orange = 4,我希望输出如下所示:

(C5): Top
(C6): Apple 1
(C7): Apple 2
(C8): Apple 3
(C9): Orange 1
(C10): Orange 2
(C11): Orange 3
(C12): Orange 4
(C13): Hello world 1
(C14): Hello world 2
(C15): Bottom

If apple+orange >6, then I want to insert empty rows above C14.如果apple+orange>6,那么我想在C14上方插入空行。 How do I do this?我该怎么做呢? This is my code so far, however when I ran it, it printed "Apple 1" to "Hello World 2" to cells C6:C17, and pushed "Bottom" down to C26.到目前为止,这是我的代码,但是当我运行它时,它将“Apple 1”打印到“Hello World 2”到单元格 C6:C17,并将“底部”推到 C26。

Private Sub CommandButton1_Click()

Dim apple As Integer, orange As Integer
Dim i As Long, j As Long, k As Long, l As Long, lRow As Long, sentence1 As Long, sentence2 As Long, addRows As Long

lRow = Cells(6, 3).End(xlUp).Row + 1
apple = InputBox("Please enter number of apples")
orange = InputBox("Please enter number of oranges")
sentence1 = 1
sentence2 = 1

fruit = apple + orange
addRows = fruit - 8
If fruit > 8 Then
    Rows("13:" & addRows).Insert Shift:=xlDown, _
        CopyOrigin:=xlFormatFromLeftOrAbove
End If

    For i = 1 To apple
        Cells(lRow, 3) = "Apple " & i
        lRow = lRow + 1
    Next i

    For j = 1 To orange
        Cells(lRow, 3) = "Orange " & j
        lRow = lRow + 1
    Next j
    
    For k = 1 To sentence1
        Cells(lRow, 3) = "Hello world 1"
        lRow = lRow + 1
    Next k
    
    For l = 1 To sentence2
        Cells(lRow, 3) = "Hello world 2"
        lRow = lRow + 1
    Next l
        
End Sub

 

You don't declare the variable addRows , but it looks like it should be an integer or a long.您没有声明变量addRows ,但它看起来应该是整数或长整数。 If you want to use such a variable in a Rows() statement, you cannot put the variable inside the double quotes, like you have here:如果你想在 Rows() 语句中使用这样的变量,你不能把变量放在双引号内,就像你在这里一样:

Rows("13:addRows").Insert Shift:=xlDown, _

Instead, use相反,使用

Rows("13:" & addRows).Insert Shift:=xlDown, _

It is not clear what you want to do here, though.不过,目前还不清楚您想在这里做什么。 What if addRows is less than 13?如果 addRows 小于 13 怎么办? then that statement does not make sense.那么这种说法就没有意义了。 You need to edit your question and explain what you want to achieve.您需要编辑您的问题并解释您想要实现的目标。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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