将宏限制为活动工作表

时间:2018-11-25 10:17:18

标签: excel vba

我在多工作表工作簿Workbook1中有一个工作表,其中包含一些VBA代码,当某些计算出的单元格的值发生变化时,这些代码就会执行。一切正常。但是,如果该工作簿处于活动状态,并且我打开了另一个与Workbook2不相关的工作簿Workbook1,则似乎Workbook1的VBA代码尝试执行,并且出现运行时错误消息框: / p>

  

“ 9:下标超出范围”

消息。如正在执行Workbook1的代码。如果在运行时错误上按DEBUG按钮,则会看到workbook1的代码。

我需要将特定VBA代码的执行限制为Workbook1FEED_ANALYSIS工作表。

其中包含Workbook1工作表所附的FEED_ANALYSIS代码。

谢谢。

Private Sub Worksheet_Calculate()
    Dim Cost_Per_day
    Dim COST_kg
    Dim COST_GROSS_kg
    Dim AVG_SALES_PRICE
    Dim COST_NET_PURCHASE
    Dim PROFIT_GROSS
    Dim PROFIT_NET
    Dim PROFIT_NET_X
    Dim Flag_set

    Dim dtmTime As Date
    Dim Rw As Long

'If Critical Cells change, move contents to Log sheet

    Dim Xrg As Range
    Set Xrg = Range("E5:I11")
    If Not Intersect(Xrg, Range("E5:I11 ")) Is Nothing Then
        dtmTime = Now()
        Cost_Per_day = Worksheets("FEED_ANALYSIS").Range("E7").Value
        COST_kg = Worksheets("FEED_ANALYSIS").Range("F7").Value
        COST_GROSS_kg = Worksheets("FEED_ANALYSIS").Range("G7").Value
        AVG_SALES_PRICE = Worksheets("FEED_ANALYSIS").Range("I5").Value
        COST_NET_PURCHASE = Worksheets("FEED_ANALYSIS").Range("G11").Value
        PROFIT_GROSS = Worksheets("FEED_ANALYSIS").Range("I7").Value
        PROFIT_NET = Worksheets("FEED_ANALYSIS").Range("I8").Value
        PROFIT_NET_X = Worksheets("FEED_ANALYSIS").Range("I9").Value

        Rw = Sheets("LOG").Range("A" & Rows.Count).End(xlUp).Row + 1

        With Sheets("LOG")
            datcomp = .Cells(Rw - 1, 1)

       ' if the previous entry date is the same as the current date, do not create the entries... one entry per day

            If Year(datcomp) = Year(dtmTime) And Month(datcomp) = Month(dtmTime) And Day(datcomp) = Day(dtmTime) Then GoTo NoUpd

            .Cells(Rw, 1) = dtmTime
            .Cells(Rw, 2) = Cost_Per_day
            .Cells(Rw, 3) = COST_kg
            .Cells(Rw, 4) = COST_GROSS_kg
            .Cells(Rw, 5) = AVG_SALES_PRICE
            .Cells(Rw, 6) = COST_NET_PURCHASE
            .Cells(Rw, 7) = PROFIT_GROSS
            .Cells(Rw, 8) = PROFIT_NET
            .Cells(Rw, 9) = PROFIT_NET_X
            .Cells(Rw, 11) = .Cells(Rw - 1, 1)
NoUpd:
        End With   
    End If
End Sub

1 个答案:

答案 0 :(得分:0)

第一次启动宏时,请在全局变量中获取工作簿名称。然后使用该变量限定要使用的wokbook头。如果您现在打开另一个工作簿,则该宏将在正确的wokbook上起作用:

    T_results=soup.findAll('h3',attrs={'class':'s-item__title'})
    Pr_results=soup.findAll('span',attrs={'class':'s-item__price'})

    for i_name in (T_results):
    for i_price in (Pr_results):