Excel VBA编程范围选择问题

时间:2015-03-31 21:14:52

标签: excel vba excel-vba

需要帮助做这件事:

  1. 打开输入框并提示用户选择从1到
  2. 的工作表编号
  3. 将用户输入的值存储在名为Index的整数类型的变量中。 您可以假设用户将始终输入有效输入(即1,2或3)。该 如果用户输入文本,程序将给出运行时错误 - 但是你这样做 不需要编写代码来处理这种情况。
  4. 使用用户输入的索引号和Worksheets()集合对象 激活选定的工作表。
  5. 在A列的列表中查找项目数(从单元格A1开始)并存储它 在名为L1的变量中;找到列B中列表中的项目数(开始 在单元格B1)中并将其存储在名为L2的变量中。
  6. 使用If语句确定要存储在名为的变量中的字符串 回答: 如果A列中的项目数较大,则“列表1更长”。 如果B列中的项目数量较大,则“列表2更长” 否则为“相同长度”。
  7. 打开一个显示答案的消息框。

1 个答案:

答案 0 :(得分:1)

嗯...

Sub HomeworkForNmHomie13()
Dim Response, Index, L1, L2, Answer
Do
    Response = InputBox("Enter a number from 1 to " & Worksheets.Count)
    If Response = "" Then Exit Sub
    'Your teacher said don't do error handling, but that's for failures.
    On Error Resume Next
    Index = Int(Response)
    On Error GoTo 0
    If Index > Worksheets.Count Or Index < 1 Then
        MsgBox ("Your entry was invalid. Please enter a number between 1 and " & Worksheets.Count)
    End If
Loop While Index > Worksheets.Count Or Index < 1
Sheets(Index).Activate
L1 = Cells(Rows.Count, "A").End(xlUp).Row 'Assuming an "item" includes blank cells
L2 = Cells(Rows.Count, "B").End(xlUp).Row 'Just grab the last row with data
'Use 2 IIF Statements to check the length using one line of code and look smart as hell
Answer = IIf(L1 > L2, "List 1 is longer", IIf(L2 > L1, "List 2 is Longer", "Same length"))
MsgBox (Answer)
End Sub

如果你愿意&#34;留下深刻印象&#34;你的老师满足最低要求:

Sub LazyHomeworkForNmHomie13()
Index = Int(InputBox("Enter a number from 1 to " & Worksheets.Count))
Sheets(Index).Activate
L1 = Cells(Rows.Count, "A").End(xlUp).Row
L2 = Cells(Rows.Count, "B").End(xlUp).Row
Answer = IIf(L1 > L2, "List 1 is longer", IIf(L2 > L1, "List 2 is Longer", "Same length"))
MsgBox (Answer)
End Sub