首页 > 解决方案 > 如何根据变量写入一系列单元格?

问题描述

我有 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

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

标签: excelvba

解决方案


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

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

推荐阅读