无法从函数中获取返回的数据

时间:2013-10-15 12:18:21

标签: excel-vba vba excel

在Sub()中使用时,我无法捕获函数的返回值。 这是我的功能。它与我的Sub()编写在同一个模块中。

Option Explicit
Public Function GetMyPath(ByVal strPath As String) As String
' Get the directory strPath from the user
' strPath is the default path given by the function argument

Dim fldr As FileDialog
Set fldr = Application.FileDialog(msoFileDialogFolderPicker)

On Error GoTo 0

With fldr
     .Title = "Selectionner un dossier"
     .AllowMultiSelect = False
     .InitialFileName = strPath
      If .Show <> -1 Then GoTo NextCode
      strPath = .SelectedItems(1)   
End With

NextCode:
Set fldr = Nothing

End Function

如您所见,它倾向于将用户选择的路径作为字符串返回。此函数正常工作,因为最终MsgBox()将正确显示所选路径。 现在我的Sub()的第一部分

Sub SaveToPDF()
'Export RngToExport as FileFormat to MyPath 

Dim ToDate As String
Dim ws As Worksheet
Dim RngSelect As Range
Dim Response As Integer
Dim Fileformat As Excel.XlFileFormat
Dim RngToExport, NameOfWorker As Variant
Dim MyPath As String



Set ws = Workbooks("Gestion_salaires.xlsm").Application.Sheets("Export")
Set RngToExport = ws.Range(Cells(1, 1), Cells(43, 7))
Set NameOfWorker = Cells(14, 19)

MyPath = "Y:\BATORA_BATURIX\Employes\Walter H. BAQUE B\bulletin_salaire\"

''We want to warn about errors before saving
If Cells(12, 21).Value <> 0 Or Cells(12, 22) <> 0 Or Cells(12, 23) > 0 Then GoTo Warning_


Response = MsgBox(Prompt:="Voulez-vous utiliser l'emplacement par défaut ?", Buttons:=vbYesNo)
    If Response = vbNo Then
    MyPath = GetMyPath("C:\")
    End If

MsgBox(MyPath) '' just for debuging. MyPath is empty :-(

我做错了什么?写Set MyPath = GetMyPath("C:\")不起作用,因为它不是一个对象。 谢谢你的帮助。

1 个答案:

答案 0 :(得分:2)

您需要插入一行,如:

GetMyPath = strPath
在结束函数之前

否则字符串不会从函数中传回。