2013-10-15 22 views
0

在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 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:\")不起作用,因为它不是一个对象。 谢谢你的帮助。

回答

2

你需要插入一行:在结束之前功能

GetMyPath = strPath 

否则,字符串不会传回功能。

+0

非常好。 TY为您的答案。一旦问题解决后,用[SOLVED]标签编辑我的问题标题是否是最佳做法? – gabx

+1

看到[这里](http://stackoverflow.com/help/someone-answers)当有人回答你的问题时该做什么 – barrowc