简体   繁体   English

将模块中的Excel VBA代码应用于所有工作表

[英]Applying Excel VBA code in a module to all worksheets

I've been struggling with this for a few days. 我已经为此苦苦挣扎了几天。
I have the below code which copies and pastes value when a certain If condition is met (the workbook has live data feeding into multiple sheets every second). 我有下面的代码,当满足某个If条件时(工作簿每秒将实时数据馈入多张纸),将其复制并粘贴值。
The code is currently located in a module, as the IF condition can apply to all sheets in the workbook. 该代码当前位于模块中,因为IF条件可以应用于工作簿中的所有工作表。

The problem I have is the code only runs on the activesheet. 我的问题是代码仅在Activesheet上运行。 I need it to run on all worksheets in the workbook. 我需要它在工作簿中的所有工作表上运行。 I've tried multiple loops with no success. 我尝试了多个循环,但均未成功。 Ideally I need the code to run across all sheets in the background (ie without activating them). 理想情况下,我需要代码在后台运行所有工作表(即不激活它们)。 Any help will be appreciated. 任何帮助将不胜感激。

Dim TimeToRun

Sub auto_open()
    Call SchedulePrices
End Sub

Sub SchedulePrices()
    TimeToRun = Now + TimeValue("00:00:15")
    Application.OnTime TimeToRun, "CopyPrice"
End Sub

Sub CopyPrice()
    Calculate

If Range("AM7") = "1" Then

    Range("AM10:AM69").Value = Range("K9:K68").Value
    Range("AL10:AL69").Value = Range("B9:AM68").Value
    Range("AM8:AM9").Value = Range("C2:C3").Value

End If

'run the timer sub
    Call SchedulePrices

End Sub

Sub auto_close()
    On Error Resume Next
    Application.OnTime TimeToRun, "CopyPrice", , False
End Sub
Sub CopyPrice()
    Dim sht as Worksheet



    For Each sht in Worksheets
        If sht.Range("AM7") = "1" Then
            sht.Calculate

            sht.Range("AM10:AM69").Value = sht.Range("K9:K68").Value
            sht.Range("AL10:AL69").Value = sht.Range("B9:AM68").Value
            sht.Range("AM8:AM9").Value = sht.Range("C2:C3").Value

        End If
    Next

'run the timer sub
    Call SchedulePrices

End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM