运行sub时出现“Argument not optional”错误

时间:2017-10-16 16:01:49

标签: vba

当我尝试运行sub(下面)时,我得到编译错误:参数不是可选的,在Set wb = getDensityTemplate()行。任何人都可以向我解释这个吗?感谢Thomas Inzina为我提供此代码。

Public Sub MultipleParts()
Dim vFiles As Variant, FileFullName As Variant
Dim NextRow As Range, wb As Workbook
Dim CalculationMode As XlCalculation
CalculationMode = ToggleEvents(False, xlCalculationManual)

vFiles = getFileList("C:\Users\OneDrive-CoorsTek\temp", "*.xls*")
If UBound(vFiles) = -1 Then
    MsgBox "No files found", vbInformation, ""
    Exit Sub
End If

Set wb = getDensityTemplate()

For Each FileFullName In vFiles
    With wb.Worksheets(1)
        'Add Header
        .Range("A1:H1").Value = Array("FileName", "Description", "WaterTemp(C)", "WaterDensity(g/cc)", "PartID", "DryMass(g)", "SuspendedMass(g)", "Density(g/cc)")
        'Target the next empty row
        Set NextRow = .Range("A" & .Rows.Count).End(xlUp).Offset(1)
        AddBatchCard CStr(FileFullName), NextRow
    End With
Next

ToggleEvents True, CalculationMode 
End Sub

还会显示getDensityTemplate子。

Private Function getDensityTemplate(FilePath As String) As Workbook
Dim SheetsInNewWorkbook As Integer
Dim wb As Workbook
SheetsInNewWorkbook = Application.SheetsInNewWorkbook
Application.SheetsInNewWorkbook = 1

Set wb = Workbooks.Add(xlWBATWorksheet)
wb.Worksheets(1).Name = "Density"
wb.SaveAs FileName:=FilePath & "DensitySummary" & Format(Now, "yyyy_mm_dd_hh.mm")
Set getDensityTemplate = wb

结束功能

1 个答案:

答案 0 :(得分:2)

如果这是您方法的签名:

Private Function getDensityTemplate(FilePath As String) As Workbook

然后FilePath参数不是可选的,因此在调用站点提供必须才能编译代码。

Set wb = getDensityTemplate("c:\dev\excel\...\somefile.xlsx")

FilePath需要的任何内容。

当您调用参数化过程时,无论是SubFunction还是Property,都必须在呼叫站点指定所有非可选参数,以便调用是有效的。

Sub Test()
    DoSomething 42 'illegal: arg2 is missing
End Sub

Sub DoSomething(ByVal arg1 As Long, ByVal arg2 As String)
    'do something
End Sub

您可以跳过指定参数的唯一时间是参数可选,例如:

Sub DoSomething(ByVal arg1 As Long, Optional ByVal arg2 As String = "SomeDefault")
    'do something
End Sub

在这种情况下,具有可选参数的过程将以可以处理未指定的参数的方式实现。如果您正在使用可选参数实施过程,则可以使用Variant函数验证是否提供了IsMissing参数:

Sub DoSomething(ByVal arg1 As Long, Optional ByVal arg2 As Variant)
    If IsMissing(arg2) Then
        'arg2 was not supplied and has no value
    Else
        'arg2 was supplied
    End If
End Sub