首页 > 解决方案 > 调用子程序的输出不正确

问题描述

我的程序旨在从 Excel 工作表中输入 GPA、学生身份和学分,并使用它们来计算给定学生的学费、费用、折扣和总金额。

我必须使用单独的子程序来解决工作表中每个人的学费、杂费、折扣和总额。

我的问题是当我尝试调用与主子程序不同的子程序并获得我需要的值时,它会显示一个随机数并且不使用访问任何部分的费用或其他子程序设置值。

我试过移动我的声明,但代码只会出现更多错误。

'Primary subroutine
Sub Proj_5p2()

'Variables
Dim dblGPA As Double
Dim strStat As String 
Dim intRow As Integer
Dim intCredHrs As Integer
Dim curTuition As Currency
Dim curFees As Currency
Dim curDisc As Currency
Dim curTotal As Currency

'Processing
Do While (Range("a" & intRow) <> "")
    'Get required input for each row
    dblGPA = Range("c" & intRow).Value
    strStat = UCase(Range("d" & intRow).Value)
    intCredHrs = Range("e" & intRow).Value

    'Call subroutines
    Call Tuition(curTuition, intCredHrs, strStat)

    'Display subroutines
    Range("f" & intRow) = curTuition
Loop

End sub

'Call from subroutine
Sub Tuition(curTuition As Currency, intCredHrs As Integer, strStat As String)

   If strStat = "GRADUATE" Then
        If intCredHrs < 18 Then
            curTuition = 335 * intCredHrs
        Else
            curTuition = 6500
    End If

    ElseIf strStat = "UNDERGRADUATE" Then
        curTuition = 550 * intCredHrs
    End If

End Sub

我需要它来根据学生的学分和大学状态来计算学生的学费。

在我的代码中,我让它用 10 个学分完成本科。这应该会导致学费为 3,350.00 美元,但结果却是 300.00 美元。

我不知道它从哪里得到300。

标签: excelvba

解决方案


很难说没有看到整个事情(数据+宏),但我敢打赌,你的主子例程中没有工作簿或工作表声明。现在它可以从其他工作表甚至打开的工作簿中读取。

我要补充:

    Sub Proj_5p2()

    ' Delcare your workbook and worksheet
    Dim wb as Workbook
    Dim ws as Worksheet
    ' If data in the same workbook as the macro,
    ' or a static name: Set wb = Workbooks("bookname.xlsx")
    Set wb = ThisWorkbook 
    Set ws = wb.Worksheets("nameofsheet")


    'Variables
    Dim dblGPA As Double
    Dim strStat As String 
    Dim intRow As Integer
    Dim intCredHrs As Integer
    Dim curTuition As Currency
    Dim curFees As Currency
    Dim curDisc As Currency
    Dim curTotal As Currency

    ' Adds the worksheet reference, now each range object with .Range
    With ws

    'Processing
    Do While (.Range("a" & intRow) <> "")
    'Get required input for each row
    dblGPA = .Range("c" & intRow).Value
    strStat = UCase(.Range("d" & intRow).Value)
    intCredHrs = .Range("e" & intRow).Value

    'Call subroutines
    Call Tuition(curTuition, intCredHrs, strStat)

    'Display subroutines
    .Range("f" & intRow) = curTuition
    Loop

    End With

结束子


推荐阅读