为什么我的Sub触发了尚未调用的其他函数?

时间:2017-11-23 03:28:40

标签: excel vba excel-vba

我有一段代码循环遍历一系列单元格,对于该范围内的每个彩色单元格,在两个模板上复制并粘贴一列,并将当前单元格的内容复制到新列中。 我的主要问题是循环到达某个点,然后以某种方式触发文档中的其他UDF,这使得代码运行得相当慢。

对于循环找到的第一个彩色单元格,它会跳过第二个If语句(如果ConstructFirst = True),触发下一个,但是在将taskName复制到目标列之后,它会跳转到尝试求和的UDF在跳转到第二个UDF之前,特定范围内的彩色单元格内的值,该UDF将几个不同的纸张上的单元相加。

这是我的代码:

taskCount = 0
ConstructFirst = False

Set ws = ThisWorkbook.Sheets("Cost Summary")
Set labourTemplate = ThisWorkbook.Sheets("Labour Template")
Set plantTemplate = ThisWorkbook.Sheets("Plant Template")

Set TaskList = ws.Range("TaskList[Work Activities]")
newLabCol = 19
newPlantCol = 13

For Each task In TaskList

    If task.Interior.ColorIndex > 0 And labourTemplate.Cells(9, newLabCol) <> task.Text Then
        taskName = task.Text
        taskID = ws.Cells(task.Row, 2)
        newLabCol = newLabCol + taskCount
        newPlantCol = newPlantCol + taskCount

        If ConstructFirst = True Then
            If labourTemplate.Cells(9, newLabCol) <> taskName Then
                labourTemplate.Range("S1:S74").Copy labourTemplate.Cells(1, newLabCol)
                labourTemplate.Cells(9, newLabCol) = taskName
                labourTemplate.Cells(8, newLabCol) = taskID
            End If
            If plantTemplate.Cells(8, newLabCol) <> taskName Then
                plantTemplate.Range("M1:M73").Copy plantTemplate.Cells(1, newPlantCol)
                plantTemplate.Cells(8, newPlantCol) = taskName
                plantTemplate.Cells(5, newPlantCol) = taskID
            End If
        taskCount = taskCount + 1
        End If

        If ConstructFirst = False And labourTemplate.Cells(9, 19) <> taskName And plantTemplate.Cells(8, 13) <> taskName Then

            labourTemplate.Cells(9, newLabCol) = taskName 'CODE TRIGGERS OTHER FUNCTIONS AFTER THIS LINE
            labourTemplate.Cells(8, newLabCol) = taskID

            plantTemplate.Cells(8, newPlantCol) = taskName
            plantTemplate.Cells(5, newPlantCol) = taskID
            ConstructFirst = True
            taskCount = taskCount + 1
        End If
    End If
Next task

这是第一个被触发的UDF。请注意,这个UDF不是我自己的工作。

Function SumCellsByColor(rData As Range, cellRefColor As Range)
Dim indRefColor As Long
Dim cellCurrent As Range
Dim sumRes
Dim rowCheck As String
Dim colCheck As String


Application.Volatile
sumRes = 0
indRefColor = cellRefColor.Cells(1, 1).Interior.Color
For Each cellCurrent In rData
    If indRefColor = cellCurrent.Interior.Color Then
        sumRes = WorksheetFunction.Sum(cellCurrent, sumRes)
    End If
Next cellCurrent

SumCellsByColor = sumRes

我在一个单元格中有这个函数,它指的是我的循环试图查看的相同范围,所以我从该单元格中移除了该函数,但它没有任何区别。我已经觉得我正在用这篇文章中显示的代码量推动它,所以如果有人需要看到第二个UDF触发请注释,我会把它提出来。我对任何类型的编码仍然缺乏经验,所以我意识到我可能没有正确地抓住可能出现的任何错误,非常感谢任何帮助。

1 个答案:

答案 0 :(得分:0)

在UDF代码中中断并检查输入范围以查看它们是否在您正在使用的范围内。

如果您在运行期间根本不需要计算,可以使用

将其关闭
 Application.Calculation = xlCalculationManual. 

完成后别忘了重置它。