Excel VBA:调用子例程时出错

时间:2013-07-23 14:14:01

标签: excel-vba scope subroutine vba excel

我遇到以下代码的问题:

我的主要代码是“autofill_DSR”,我试图调用的子程序是“算法”。 “autofill_DSR”在Module1中,“算法”在Module4中。 以前,我没有将这两个代码分开,我只是在“算法”中有很多内容 在我写的那一行:调用Module4.algorithm,程序做了我想要的。

创建此子例程后,它只进行一次代码迭代,但是, 因为它执行一次子程序但它没有返回或存在问题 在for循环中迭代。我无法理解。

我使用“Sheet2”激活命令,因为当我进入子程序时,我在工作表之间切换, 可能与它有关,可能是公共/私人变量声明吗?

感谢任何帮助,谢谢。


Sub autofill_DSR()

' Variable Declarations:

Dim x_count As Integer
Dim n As Integer
Dim item_a As String
Dim item_b As String
Dim test_string As String

' Variable Initializations:

test_string = "NN"
x_count = 0
Process_Control_NumRows = 16

' Main Data Transfer Code:

Sheets(Array("Sheet1", "Sheet2")).Select        'Create Array of all Sheets

' Process Control Sheet:

    For n = 0 To (Process_Control_NumRows - 1)  'Cycle 16 times for each
                                                'item in process controls tab
        Sheets("Sheet2").Activate       'Choose specific sheet
        Range("D1").Select              'Choose specific cell

        Call Module4.algorithm      'Call on subroutine (see algorithm code)

    Next n                  'increment index to account for offset

End Sub

Sub algorithm()

        'If an "x" or "X" is marked in the "Yes" column,
        'at descending cells down the column offset by the for loop index, n

        If (ActiveCell.Offset(n, 0) = "x" Or ActiveCell.Offset(n, 0) = "X") Then

            item_a = ActiveCell.Offset(n, -3).Value     ' Store Letter value
            item_b = ActiveCell.Offset(n, -2).Value     ' Store number value
            x_count = x_count + 1                       ' increment the total x count

            If (x_count > 5) Then

                Sheets("Sheet3").Activate               ' Switch over to Sheet 1
                Range("A1").Select                      ' Choose "Item" column, first cell
                ActiveCell.Offset((x_count - 6), 0).Value = (item_a & item_b)

                'Insert cocatenated value of item_a and item_b
                '(for example "A" & "1" = "A1")
                'at the cells under the "Item" column, indexed by x_count

            Else

                Sheets("Sheet1").Activate
                Range("A1").Select
                ActiveCell.Offset((x_count - 1), 0).Value = (item_a & item_b)

            End If

        End If

End Sub

1 个答案:

答案 0 :(得分:1)

Sub algorithm()更改为Sub algorithm(n as long),然后使用

调用它
Call Module4.algorithm(n)