我使用workbookA
方法每隔1分钟将数据从workbookB
复制并粘贴到application.ontime
。但是,当我运行此宏时,我正在workbookC
完全不同的工作。每次宏运行时,会弹出workbookB
,这会干扰我在workbookC
上执行的操作。它会让人感到沮丧......有没有办法解决这个问题?
我的代码具有以下结构:
sub dataextract()
ThisWorkbook.Activate 'ThisWorkbook is workbookA
'copy the data
If workbookB Is Nothing Then
Set workbookB= Workbooks.Open("C:\Users\Ken\Desktop\Df.xlsx")
Else
Set workbookB= Workbooks("Df.xlsx")
End If
workbookB.Activate
'paste the data here
workbookB.Save
timer 'timer is the sub that contains the application.ontime loop
end sub
有什么建议吗?
答案 0 :(得分:0)
您有两个选项可以停止闪烁,使用以下功能,关闭屏幕更新(该功能还包括其他一些功能,但不要忘记将其重新打开)。
Sub SetEvents(ByVal State As Boolean)
With Excel.Application
.ScreenUpdating = State
.EnableEvents = State
If State = True Then .Calculation = xlCalculationAutomatic Else .Calculation = xlCalculationManual
End With
End Sub
或停止使用activeworkbook / select range方法。如果您正确定义了引用,即
Workbooks("Mybook.xlsx").Sheets("Sheet1").Range("A1").copy
由于工作簿实际上没有改变,闪烁将停止。
如果你想要包含第一个选项,根据你的评论,在sub之外添加函数并调用它,如下所示:
sub dataextract()
setEvents False
ThisWorkbook.Activate 'ThisWorkbook is workbookA
'copy the data
If workbookB Is Nothing Then
Set workbookB= Workbooks.Open("C:\Users\Ken\Desktop\Df.xlsx")
Else
Set workbookB= Workbooks("Df.xlsx")
End If
workbookB.Activate
'paste the data here
workbookB.Save
timer 'timer is the sub that contains the application.ontime loop
setEvents True
end sub
Sub SetEvents(ByVal State As Boolean)
With Excel.Application
.ScreenUpdating = State
.EnableEvents = State
If State = True Then .Calculation = xlCalculationAutomatic Else .Calculation = xlCalculationManual
End With
End Sub
答案 1 :(得分:0)
sub dataextract()
dim xl as application
dim workbookB as workbook
'ThisWorkbook.Activate 'ThisWorkbook is workbookA, unnecessary to activate workbook when you copy
'copy the data
If workbookB Is Nothing Then
set xl = new application 'create another excel application
xl.visible = false 'set the new excel application invisible
Set workbookB= xl.Workbooks.Open("C:\Users\Ken\Desktop\Df.xlsx")
Else
Set workbookB= xl.Workbooks("Df.xlsx")
End If
'workbookB.Activate 'unnecessary to activate workbook when you paste
'paste the data here
workbookB.Save
timer 'timer is the sub that contains the application.ontime loop
end sub