2017-01-11 64 views
0

我正在嘗試嵌入我的代碼。我創建了一個名爲JrnlHeader的子例程來聲明我將在另一個子例程中使用的變量。我目前只關注一個名爲Header的變量。我想知道爲什麼Header在子程序PrintToTextFile中爲空,以及我如何修復它以便能夠使用在JrnlHeader中聲明的字符串。將字符串傳遞給另一個子例程

Private Sub JrnlHeader() 
    Dim Header As String 
    Dim SeqNo As String 
    Dim SeqVar As String 
    Dim Bu As String 
    Dim BuVar As String 
    Dim JrnlID As String 
    Dim JrnlIDVar As String 
    Dim JrnlDate As String 
    Dim JrnlDateVar As String 
    Dim Descr As String 
    Dim DescrVar As String 
    Dim Ledger As String 
    Dim LedgerVar As String 
    Dim Source As String 
    Dim SourceVar As String 
    Dim CurEff As String 
    Dim Reverse As String 
    Dim AutoLn As String 
    Dim AdjEnt As String 

    Header = "<JRNL_HDR_IMP>" 
    SeqNo = "<SEQNO>" & SeqVar & "</SEQNO>" 
    Bu = "<BUSINESS_UNIT>" & BuVar & "</BUSINESS_UNIT>" 
    JrnlID = "<JOURNAL_ID>" & JrnlIDVar & "</JOURNAL_ID>" 
    JrnlDate = "<JOURNAL_DATE>" & JrnlDateVar & "</JOURNAL_DATE>" 
    Descr = "<DESCR254>" & DescrVar & "</DESCR254>" 
    Ledger = "<LEDGER_GROUP>" & LedgerVar & "</LEDGER_GROUP>" 
    Source = "<SOURCE>" & SourceVar & "</SOURCE>" 
    CurEff = "<CUR_EFFDT>" & JrnlDateVar & "</CUR_EFFDT>" 
    Reverse = "<REVERSAL_CD>N</REVERSAL_CD>" 
    AutoLn = "<AUTO_GEN_LINES>N</AUTO_GEN_LINES>" 
    AdjEnt = "<ADJUSTING_ENTRY>N</ADJUSTING_ENTRY>" 
End Sub 

Sub PrintToTextFile() 
    Dim FileNum As Integer 

    JrnlHeader 

    FileNum = FreeFile ' next free filenumber 

    'Open "C:\Temp\TEXTFILE.TXT" For Output As #FileNum ' creates the new file 
    Open "C:\temp\TEXTFILE.TXT" For Append As #FileNum 
    Print #FileNum, Header 
    Close #FileNum ' close the file 
End Sub 

回答

0

這兩個子程序有不同的範圍。定義JrnlHeader的變量在PrintToTextFile中不可用。如果您希望在PrintToTextFile中使用標題,請將其更改爲PrintToTextFile(標題爲字符串)並從JrnlHeader調用PrintToTextFile(標題)。

1

您已經定義Header是在JrnlHeader一個局部變量。這意味着它的範圍不會擴展到其他子程序/功能。

通過將Dim Header As String語句放在代碼模塊中的第一個子例程/函數之前,可以將該變量的範圍定義爲「模塊」級別。然後在PrintToTextFile繼續執行時,其值將可用。


或者,你可以改變你的代碼的變量傳遞的兩個函數之間的參數:

Sub PrintToTextFile() 

    Dim Header As String 
    '... 
    JnrlHeader Header 
    '... 
    Print #FileNum, Header 
End Sub 

Sub JrnlHeader(Header As String) 
    '... (but don't include any declaration of Header!) 
    Header = "<JRNL_HDR_IMP>" 
    '... 
End Sub 

但是,通過判斷有多少變數正在建立在JrnlHeader,我想你將希望使用模塊級範圍變量方法。

相關問題