简体   繁体   中英

How to call a subroutine that has parameters?

I am working on an Excel Userform to generate a report for a lot entered on a given day.

The report is stored in a Word document which contains the results of between 1 and 8 quality samples (number of samples varies by lot).

The Userform is meant to load in Excel, receive a lot number and date from the user, retrieve samples from that day and lot from a different sheet in the Excel workbook and then copy the data into a new Word doc based on a custom template.

The input part of the Userform and the Word template are both set up. I hit a snag on the event handling procedure for the "OK" button.

The form's OK button event handler gives

compile error

on

Sub makeReport(lNum As Integer, pDay As Date)

The editor isn't indicating an issue in my makeReport method; the call to makeReport in the event handler is highlighted red.

I am using the Excel 2013 VBA editor, and neither the built-in debugging tools in Excel, the Microsoft online VBA docs nor various forum posts found via Google can give me a complete answer to what is wrong and how to fix it.

OK Button event handler

Private Sub OKButton_Click() 'OK button
    'Declare variables
    Dim lNum As Integer
    Dim pDay As Date
    Dim name As String
    Dim nStr As String
    Dim dStr As String
    
    'Error handler for incorrect input of lot number or pack date
    On Error GoTo ErrorHandler
    
    'Convert input values to correct types
    nStr = TextBox1.Value
    dStr = TextBox2.Value
    
    'Set variable values
    lNum = CInt(nStr)
    
    MsgBox ("Step 1 Done" + vbCrLf + "Lot Number: " + nStr)
    
    pDay = Format(dStr, "mm/dd/yyyy")
    
    MsgBox ("Step 2 Done" + vbCrLf + "Pack Date: " + dStr)
    
    name = nameDoc(pDay, lNum)
    
    MsgBox ("Step 3 Done" + vbCrLf + "Report Name: " + name)
    
    'Check for existing report
    If Dir("\\CORE\Miscellaneous\Quality\Sample Reports\" + name) Then
        MsgBox ("The file " + name + "already exists. Check \\CORE\Miscellaneous\Quality\Sample Reports for the report.")
        Unload UserForm1
        Exit Sub
    Else
        makeReport(lNum, pDay)
    End If
    
    'Unload User Form and clean up
    Unload UserForm1
    Exit Sub
ErrorHandler:
    MsgBox ("Error. Please Try Again.")
    'Unload UserForm1
End Sub

makeReport sub

Sub makeReport(lNum As Integer, pDay As Date)
    
    'Template Path: \\CORE\Miscellaneous\Quality\Sample Reports\Template\Defect Report.dotm
    'Save path for finished report: \\CORE\Miscellaneous\Quality\Sample Reports
    'Generate doc name
    
    Dim name As String
    name = nameDoc(pDay, lNum)
    
    'Initialize word objects and open word
    Dim wApp As Word.Application
    Dim wDoc As Word.Document
    
    Set wApp = CreateObject("Word.Application")
    wApp.Visible = True
    Set wDoc = wApp.Documents.Add(Template:=("\\CORE\Miscellaneous\Quality\Sample Reports\Template\Defect Report.dotm"), NewTemplate:=False, DocumentType:=0)
    
    'Initialize excel objects
    Dim wbBook As Workbook
    Dim wsSheet As Worksheet
    
    Set wbBook = ThisWorkbook
    Set wsSheet = wbBook.Worksheets("Defect Table")
    
    'Fill in lot number and date at top of report
    With wDoc
        .Application.Selection.Find.Text = "<<date>>"
        .Application.Selection.Find.Execute
        .Application.Selection = pDay
        .Application.Selection.EndOf
    
        .Application.Selection.Find.Text = "<<lot>>"
        .Application.Selection.Find.Execute
        .Application.Selection = lNum
    End With
    
    'Initialize loop variables
    Dim row1 As Integer
    Dim row2 As Integer
    Dim diff As Integer
    Dim more As Boolean
    Dim num As Integer, num1 As Integer, col As Integer
    Dim count As Integer
    
    count = 0
    diff = 0
    more = False
        
    'Do while loop allows variable number of samples per day
    Do While count < 8
        
        'Checks for correct starting row of day
        row1 = WorksheetFunction.Match(lNum, wsSheet.Range(), 0)
        row2 = WorksheetFunction.Match(pDay, wsSheet.Range(), 0)
        
        If IsError(row1) Or IsError(row2) Then
            'Breaks for loop once all samples have been copied over
            Exit Do
            
        ElseIf row1 = row2 Then
            num = 4
            num1 = num
            Do While num < 31
                'Column variable
                col = count + 1
                
                'Copies data to word doc, accounting for blank rows in the word table
                Select Case num
                    Case 6, 10, 16, 22, 30
                        num1 = num1 + 1
                    Case Else
                        num1 = num1
                End Select
                
                ActiveDocument.Tables(1).Cell(num1, col) = ActiveSheet.Range().Cells(row1, num)
                num = num + 1
            Next
        Else
            'Deiterates count to adjust for differences between row1 and row2
            count = count - 1
        End If
            
        'Moves the collision to below row1 to allow MATCH to find next viable result
        diff = row1 + 1
        wsSheet = wsSheet.Range().Offset(diff, 0)
        
        'Iterates count
        count = count + 1
        
    Loop
    
    'Zeroes out word objects
    Set wdDoc = Nothing
    Set wdApp = Nothing
    
    'Saves Document using regular name format for ease of access
    wDoc.SaveAs2 Filename:="\\CORE\Miscellaneous\Quality\Sample Reports\" + name, FileFormat:=wdFormatDocumentDefault, AddtoRecentFiles:=False
    
End Sub
makeReport(lNum, pDay)

The brackets here imply that you are expecting something to be returned which can't happen as makeReport is a Sub not a Function . This is causing the compile error. To correct just remove the brackets.

You also have an additional problem as there is a mismatch with pDay . When you format a date you convert it from a Date , which is just a numeric value, into a String .

In OKButton_Click() try changing:

pDay = Format(dStr, "mm/dd/yyyy")

to:

pDay = CDate(dStr)

so that it matches the data type expected by makeReport . You can then apply the required formatting in makeReport by changing

.Application.Selection = pDay

to

.Application.Selection = Format(pDay, "mm/dd/yyyy")

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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