簡體   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