从另一个子例程中调用VBA子例程不起作用

我正在使用VBA尝试从主子例程调用一系列子例程。 当我把所有的子程序和下面的代码结合起来的时候,我得到#N / A代表公式被忽略。

Sub Main() 'Turn off autocalculation Application.Calculation = xlCalculationManual Application.DisplayStatusBar = False '********************************************************* 'A bunch of other code '********************************************************* Call Sub_Routine1 Call Sub_Routine2 Call Sub_Routine3 Call Sub_Routine4 Call Sub_Routine5 Call Sub_Routine6 Call Sub_Routine7 'This is the sub routine that is not working correctly Call Material_Formulas 'Turn back on the autocalculation function Application.Calculation = xlAutomatic '********************************************************* 'A bunch of other code '********************************************************* Application.DisplayStatusBar = True Application.ScreenUpdating = True Application.EnableEvents = True End Sub 

Combined_Call

当我从Main子例程中删除Material_Formulas子例程并使用下面的脚本单独运行它时,它将按照原来的方式执行,如下图所示。

 Private Sub Material_Formulas() 'Turn on manual calculation Application.Calculation = xlCalculationManual Dim lRow As Integer Dim tiesMaterial As String Dim result As String lRow = Sheets("Material").Range("A2").End(xlDown).Row lCol = Sheets("Material").Range("A2").End(xlToRight).Column 'Starts the count at column CU endCount = lCol - 1 For c = 99 To endCount For r = 3 To lRow tiesMaterial = Cells(r, 87).Value 'Looks to see if the cells starting at CU2 contains a number and then iterates through each cell in row 3 to add a formula If tiesMaterial = "TIES MATERIAL" Then 'Defines the unique ID and calendar year cells for the index-match-match function materialID = Sheets("Material").Cells(r, "CQ").Address(False, False) materialYear = Sheets("Material").Cells(2, c).Address(False, False) 'Starting in cell CU3 it adds the formula =INDEX(BOM_Summary_Array,MATCH(CQ3,BOM_Summary_ID,0),MATCH(CU2,BOM_Summary_Head,0)) Sheets("Material").Cells(r, c).Formula = "=INDEX(BOM_Summary_Array,MATCH(Material!" & materialID & ",BOM_Summary_ID,0),MATCH(Material!" & materialYear & ",BOM_Summary_Head,0))" End If Next r Next c 'Turn on the auto calculation function Application.Calculation = xlAutomatic End Sub 

Separate_Call

我究竟做错了什么? 当我手动和独立地select它的时候它是如何运行的,但是当我把它和其他的子程序结合起来时它失败了?

在任何其他事情之前,你需要改进你的代码。 我几乎可以保证,这可能是由于写得不好的代码。 例如:

 materialID = Sheets("Material").Cells(r, "CQ").Address(False, False) materialYear = Sheets("Material").Cells(2, c).Address(False, False) 

请注意, materialIDmaterialYear永远不会被声明。 这意味着它们是Varianttypes(因为这个原因,您需要将Option Explicit添加到代码模块的顶部)。 关于变体的有趣的事情是,他们,你猜对了,变化。 MaterialID可以是stringintlongdecimaldatearrayrange等。

此外,请注意讨厌的Sheets("Material") 。 这实际上是说ActiveWorkboook.Sheets(“材料”)。 validation你的参考资料,否则你几乎不知道实际发生的事情。

在你的代码中很容易发生的事情是,地址正确地作为一个string进入materialID ,但是它是另一个工作簿中名为“Material”的表的地址。 不太可能,但可能。

我们所知道的很可能是ActiveWorkbook在某种程度上正在发生变化,可能在Sub_Routine7 (这里的Sub_Routine7必须描述性地命名子例程,否则你的代码远不是可维护性)。

祝你好运,但我强烈build议不要试图debugging的情况,直到你有限的范围,声明所有的variables,并添加Option Explicit