繁体   English   中英

如何根据变量写入一系列单元格?

[英]How to write to a range of cells based on a variable?

我有2个变量。 例如:苹果=3,橙=2

我想将以下文本写入一系列单元格:(A1):苹果数量 1(A2):苹果数量 2(A3):苹果数量 3(A4):橙子数量 1(A5):数量橙子 2

现在这就是我的代码中的内容:

Dim apple As Integer
apple = InputBox("Please enter number of apples")
Range ("A1").Value = "Number of apples" & apple

Dim orange As Integer
orange = InputBox("Please enter number of oranges")
Range ("A2").Value = "Number of oranges" & orange

我想我需要创建一个循环来获得所需的结果。 有人可以指出我正确的方向吗?

您需要添加循环来添加苹果和橙子。 尝试以下代码-

Sub FillFruits()
Dim apple As Integer, orange As Integer
Dim i As Long, j As Long, lRow As Long

lRow = Cells(Rows.Count, 1).End(xlUp).Row + 1
apple = InputBox("Please enter number of apples")
orange = InputBox("Please enter number of oranges")

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

    For j = 1 To orange
        Cells(lRow, 1) = "Orange " & j
        lRow = lRow + 1
    Next j

End Sub

暂无
暂无

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

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