2013-10-15 23 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