【问题标题】:Can't pass variables from one sub to another in same module无法在同一模块中将变量从一个子传递到另一个子
【发布时间】:2015-08-02 16:33:26
【问题描述】:

我拥有的代码可以作为单独的程序很好地工作。我决定将这 2 个过程结合起来,因为代码几乎相同,但在将单元格复制到数组以保存到不同的日志表中存在一些差异。每个程序都有一个Inputbox 来获取感兴趣的年份(2014、2015、2016 ......),如果日志不存在,将用于打开 AND 使用年份代码从主服务器保存一个新的在文件名中。

基于单元格值,我正在执行If_Then_Else 以确定运行一个过程或两者。如果我将它们作为单独的程序单独运行,它们可以正常工作。当我将它们组合在一起时,我决定从内部 (SaveToLog_Replc) 调用一个过程 (SaveToLog_Audit)。我从 (SaveToLog_Audit) 中删除了日期输入,让 (SaveToLog_Replc) 获取该日期代码并传递它。我不想让 (SaveToLog_Audit) 在它运行时第二次要求约会,因为我基本上希望它不显眼(当我可以将 Ans 传递给它时,无需询问两次。

我尝试设置 public Ans 并在开始时使用 Explicit 与同一模块中的两个过程 --> 不起作用。我在选项 Explicit 之后尝试了 Dim Ans As String --> 不起作用。我尝试将 Public Ans as String --> 没有用。无论我尝试什么,我几乎都无法让它传递变量“Ans”。我对 VBA 编码还是很陌生,所以任何帮助都会很棒。显示基本代码,只显示有问题的部分。

 Option Explicit
 Public Ans As String

 Public Sub SaveToLog_Replc()

 '  Determine scrap and whether to save to Replacement_Credit tracking log
 Dim ScrapQty As Range
 '  Date entry for proper Dated log save
 Dim Ans As String
 Dim c As Boolean
 Dim fs As Object
 '  Declares path, newFile and fName variables
 Dim path As String, newFile As String, fName As String
 Set Sheet2 = ActiveSheet
 Set ScrapQty = Worksheets("Main").Range("M_Qty_Scrap")
 Application.ScreenUpdating = False
 '  >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    Ans = InputBox("Enter Log Year" & _
     "" & vbCrLf, "Year Selection", Format(Date, "YYYY"))
       If Ans = "" Then
          Exit Sub
       End If
 '  >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
    '  If scrap qty is greater than Zero (0) save to both Logs
    If ScrapQty > 0 Then
    ' If True
       MsgBox "Saving to Replacement Log and Audit Log"
    ' xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    '    Save to Audit Log then Save to Replacement Log
      '  --> 'Ans' VALUE NEEDS TO PASS TO THE PROCEDURE
      '  --> 'Ans' DOES NOT PASS TO THIS PROCEDURE AT END OF MODULE
   Call SaveToLog_Audit
    ' xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    ' +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    '  Sub routine to Save Data to Replacement Log
    '  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    '     Load Array code here for SaveToLog_Replc
    '  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    '  ***************************************************************
       'Check if Replacement Log exists. If not open Master, rename then save it. If it exists open it.
        Set fs = CreateObject("Scripting.FileSystemObject")
        '  Filename to check for
        c = fs.fileExists("S:\RECORDS\Logs\Replacement Log " & Ans & ".xls")
          If Not c Then
             'MsgBox "The file doesn't exist!"
             '  File doesn't exist. Open the Blank Master
             Workbooks.Open Filename:="S:\RECORDS\Logs\_MASTER Replacement Log.xls"
             fName = "Replacement Log " & Ans & ".xls"              ' Set fName to new FileName
             newFile = fName                                                  ' Sets new filename as fName
             path = "S:\RECORDS\Logs\"                                   ' Path to Incoming Audit Logs
             ActiveWorkbook.SaveAs Filename:=path & newFile     ' Saves as newFile
          Else
             'MsgBox "The file exists! Saving data to it."
             Workbooks.Open Filename:="S:\RECORDS\Logs\Replacement Log " & Ans & ".xls"
          End If
    '  ***************************************************************
    '  Unprotect Sheet and Show All Data code here
    '     Find LastRow. Set NextCell position code here
    '  Set the size of the new array and copy MyAr code here
    '     Draw Border Code here
    '  **********************************************
    ActiveWorkbook.Save      ' Saves Destination Workbook
    ActiveWindow.Close       ' Closes Destination Workbook
    Application.ScreenUpdating = True
    '  Confirms Save to Log File
    MsgBox "Your Data has been saved to the Log File: " & vbCrLf & vbCrLf _
    & "'Replacement Log " & Ans & ".xls'", vbInformation, "Log Save Confirmation"
    ' +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
    Else
       ' If False
       MsgBox "Saving to Audit Log Only."
    ' xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
      ' Save to Audit Log as Normal
      '  --> 'Ans' VALUE NEEDS TO PASS TO THE PROCEDURE
      '  --> 'Ans' DOES NOT PASS TO THIS PROCEDURE AT END OF MODULE
   Call SaveToLog_Audit
    ' xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
    End If
 End Sub

 Public Sub SaveToLog_Audit()
 '  Date entry for proper Dated log save
 Dim Ans As String
 Dim c As Boolean
 Dim fs As Object
 '  Declares path, newFile and fName variables
 Dim path As String, newFile As String, fName As String
 Set Sheet2 = ActiveSheet
 Application.ScreenUpdating = False
    '  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    '     Load Array code here for SaveToLog_Audit
    '  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    '  For debug
    '  --> 'Ans' DOES NOT PASS FROM (SaveToLog_Replc) PROCEDURE IN THIS MODULE
     MsgBox "The value of Ans is: " & vbCrLf & vbCrLf & "'" & Ans & "'"
    '  ********************************************************
     '  Checks if Log File exists. If not open the Master, rename then save it. If it exists open it.
     Set fs = CreateObject("Scripting.FileSystemObject")
     '  Filename to check for
     c = fs.fileExists("S:\RECORDS\Logs\" & Ans & " Audit Log.xls")
       If Not c Then
          'MsgBox "The file doesn't exist!" original code
          '  File doesn't exist. Open the Blank Master
          Workbooks.Open Filename:="S:\RECORDS\Logs\_Master Audit Log.xls"
          '  Set fName to new FileName
          fName = Ans & " Audit Log.xls"
          '  Sets new filename as fName saves to this directory
          newFile = fName
          '  Path to Incoming Audit Logs
          path = "S:\RECORDS\Logs\"
          '  Saves Blank Master as newFile
          ActiveWorkbook.SaveAs Filename:=path & newFile
       Else
          'Workbooks.Open "C:\filename.xls"
          Workbooks.Open Filename:= _
          "S:\RECORDS\Logs\" & Ans & " Audit Log.xls"
       End If
    '  ********************************************************
    '  Unprotect Sheet and Show All Data code here
    '     Find LastRow. Set NextCell position code here
    '  Set the size of the new array and copy MyAr code here
    '     Draw Border Code here
    '  **********************************************
    ActiveWorkbook.Save     ' Saves Destination Workbook
    ActiveWindow.Close      ' Closes Destination Workbook
    Application.ScreenUpdating = True
    '  Confirms Save to Log File
    MsgBox "Your Data has been saved to the Log File: " & vbCrLf & vbCrLf _
    & "'" & Ans & " Audit Log.xls'", vbInformation, "Log Save Confirmation"
 End Sub

【问题讨论】:

    标签: vba excel


    【解决方案1】:

    我建议你删除 Public 声明并将第二个例程更改为采用 String 参数:

    Option Explicit
    
     Public Sub SaveToLog_Replc()
    
     '  Determine scrap and whether to save to Replacement_Credit tracking log
     Dim ScrapQty As Range
     '  Date entry for proper Dated log save
     Dim Ans As String
     Dim c As Boolean
     Dim fs As Object
     '  Declares path, newFile and fName variables
     Dim path As String, newFile As String, fName As String
     Set Sheet2 = ActiveSheet
     Set ScrapQty = Worksheets("Main").Range("M_Qty_Scrap")
     Application.ScreenUpdating = False
     '  >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
        Ans = InputBox("Enter Log Year" & _
         "" & vbCrLf, "Year Selection", Format(Date, "YYYY"))
           If Ans = "" Then
              Exit Sub
           End If
     '  >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>
        '  If scrap qty is greater than Zero (0) save to both Logs
        If ScrapQty > 0 Then
        ' If True
           MsgBox "Saving to Replacement Log and Audit Log"
        ' xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
        '    Save to Audit Log then Save to Replacement Log
          '  --> 'Ans' VALUE NEEDS TO PASS TO THE PROCEDURE
          '  --> 'Ans' DOES NOT PASS TO THIS PROCEDURE AT END OF MODULE
       Call SaveToLog_Audit(Ans)
        ' xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
        ' +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
        '  Sub routine to Save Data to Replacement Log
        '  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        '     Load Array code here for SaveToLog_Replc
        '  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        '  ***************************************************************
           'Check if Replacement Log exists. If not open Master, rename then save it. If it exists open it.
            Set fs = CreateObject("Scripting.FileSystemObject")
            '  Filename to check for
            c = fs.fileExists("S:\RECORDS\Logs\Replacement Log " & Ans & ".xls")
              If Not c Then
                 'MsgBox "The file doesn't exist!"
                 '  File doesn't exist. Open the Blank Master
                 Workbooks.Open Filename:="S:\RECORDS\Logs\_MASTER Replacement Log.xls"
                 fName = "Replacement Log " & Ans & ".xls"              ' Set fName to new FileName
                 newFile = fName                                                  ' Sets new filename as fName
                 path = "S:\RECORDS\Logs\"                                   ' Path to Incoming Audit Logs
                 ActiveWorkbook.SaveAs Filename:=path & newFile     ' Saves as newFile
              Else
                 'MsgBox "The file exists! Saving data to it."
                 Workbooks.Open Filename:="S:\RECORDS\Logs\Replacement Log " & Ans & ".xls"
              End If
        '  ***************************************************************
        '  Unprotect Sheet and Show All Data code here
        '     Find LastRow. Set NextCell position code here
        '  Set the size of the new array and copy MyAr code here
        '     Draw Border Code here
        '  **********************************************
        ActiveWorkbook.Save      ' Saves Destination Workbook
        ActiveWindow.Close       ' Closes Destination Workbook
        Application.ScreenUpdating = True
        '  Confirms Save to Log File
        MsgBox "Your Data has been saved to the Log File: " & vbCrLf & vbCrLf _
        & "'Replacement Log " & Ans & ".xls'", vbInformation, "Log Save Confirmation"
        ' +++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
        Else
           ' If False
           MsgBox "Saving to Audit Log Only."
        ' xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
          ' Save to Audit Log as Normal
          '  --> 'Ans' VALUE NEEDS TO PASS TO THE PROCEDURE
          '  --> 'Ans' DOES NOT PASS TO THIS PROCEDURE AT END OF MODULE
       Call SaveToLog_Audit(Ans)
        ' xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx
        End If
     End Sub
    
     Public Sub SaveToLog_Audit(Ans As String)
     '  Date entry for proper Dated log save
     Dim c As Boolean
     Dim fs As Object
     '  Declares path, newFile and fName variables
     Dim path As String, newFile As String, fName As String
     Set Sheet2 = ActiveSheet
     Application.ScreenUpdating = False
        '  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        '     Load Array code here for SaveToLog_Audit
        '  ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
        '  For debug
        '  --> 'Ans' DOES NOT PASS FROM (SaveToLog_Replc) PROCEDURE IN THIS MODULE
         MsgBox "The value of Ans is: " & vbCrLf & vbCrLf & "'" & Ans & "'"
        '  ********************************************************
         '  Checks if Log File exists. If not open the Master, rename then save it. If it exists open it.
         Set fs = CreateObject("Scripting.FileSystemObject")
         '  Filename to check for
         c = fs.fileExists("S:\RECORDS\Logs\" & Ans & " Audit Log.xls")
           If Not c Then
              'MsgBox "The file doesn't exist!" original code
              '  File doesn't exist. Open the Blank Master
              Workbooks.Open Filename:="S:\RECORDS\Logs\_Master Audit Log.xls"
              '  Set fName to new FileName
              fName = Ans & " Audit Log.xls"
              '  Sets new filename as fName saves to this directory
              newFile = fName
              '  Path to Incoming Audit Logs
              path = "S:\RECORDS\Logs\"
              '  Saves Blank Master as newFile
              ActiveWorkbook.SaveAs Filename:=path & newFile
           Else
              'Workbooks.Open "C:\filename.xls"
              Workbooks.Open Filename:= _
              "S:\RECORDS\Logs\" & Ans & " Audit Log.xls"
           End If
        '  ********************************************************
        '  Unprotect Sheet and Show All Data code here
        '     Find LastRow. Set NextCell position code here
        '  Set the size of the new array and copy MyAr code here
        '     Draw Border Code here
        '  **********************************************
        ActiveWorkbook.Save     ' Saves Destination Workbook
        ActiveWindow.Close      ' Closes Destination Workbook
        Application.ScreenUpdating = True
        '  Confirms Save to Log File
        MsgBox "Your Data has been saved to the Log File: " & vbCrLf & vbCrLf _
        & "'" & Ans & " Audit Log.xls'", vbInformation, "Log Save Confirmation"
     End Sub
    

    【讨论】:

    • 我也试过你的方法,Rory。它也有效。我可以将这些程序分开并将它们放在我喜欢做的自己的模块中。
    【解决方案2】:

    您是否完全按照您发布的方式运行代码?如果是,那么问题可能是您正在发布公共 ans,然后您在第一个 sub 中使用 dim ans,稍后您将值分配给 dim Ans 而不是公共 Ans,它们是两个单独的变量。 从两个子程序中删除暗淡的 Ans,它应该可以工作

    【讨论】:

    • 我发誓我至少在其中一个程序上尝试过。这就是 KKowalczyk 的诀窍。在尝试了大约 10 种方法来传递该变量之后,我花了很多时间拉扯我剩下的一点头发。荣誉和非常感谢。我想这就是我试图在没有任何正式课业的情况下自学 VBA 的结果。当然是一种学习体验。
    • 不用担心,你不需要任何正式的课程来学习 vba,你所需要的只是像我一样有足够的问题来训练:) PS。如果解决方案,将不胜感激标记为答案
    • 我确实觉得这种自学几乎更好,因为我正在做“实际应用”工作而不仅仅是示例代码。学习样本仍然需要了解如何在实际工作文档中应用这些 sn-ps。我发现我学得越多,我回去升级我已经编码的文档就越多。让我的思绪继续运转。喜欢这个东西。我想我正确地将其标记为已回答。如果不是,我想我不知道该怎么做。
    • 是的,你做得对,谢谢:) 发现我自己的教程不是很有用,直到我遇到了这个问题,所以从理论上学习它们并没有真正有用也没有乐趣:)
    • 随着文档的投入使用,它肯定有助于挑战我的“学习”,然后我会得到反馈。这极大地推动了我的学习曲线。最好的部分是大量较小的代码模块/子例程,我只是喜欢在正确的地方即插即用,有时只需稍加调整就能让它们做我想做的事。处理 If-Then-Else 仍然让我有点。该文件现在完美运行。没有崩溃,没有挂断和变量在他们应该的时间和地点传递。我喜欢他们付钱让我学习这些东西。 谢谢你的帮助。
    猜你喜欢
    • 2018-01-14
    • 1970-01-01
    • 2018-10-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-11-27
    • 1970-01-01
    相关资源
    最近更新 更多