我正忙于尝试根据VBA上整个范围内的单元格值编写调用不同宏的代码。
因此,对于示例,我有一个范围S20:S21。
当单元格S20中的值等于1时,我想调用macro1。 当单元格S21中的值等于2时,我想调用macro2。
当没有匹配时,我有时间会在接下来的5秒内再次测试它,从顶部开始检查单元格S20是1还是S20是2。
这是我目前的代码。
Dim TimeToRun
Sub auto_open()
Call ScheduleCopyPriceOver
End Sub
Sub ScheduleCopyPriceOver()
TimeToRun = Now + TimeValue("00:00:05")
Application.OnTime TimeToRun, "CopyPriceOver"
End Sub
Sub CopyPriceOver()
Application.ScreenUpdating = False
Number = Range("S20:S22").Value
If Number = 1 Then
Call Macro1
Call ScheduleCopyPriceOver
ElseIf Number = 2 Then
Call Macro2
Call ScheduleCopyPriceOver
Else
Call ScheduleCopyPriceOver
End If
End Sub
Sub auto_close()
On Error Resume Next
Application.OnTime TimeToRun, "CopyPriceOver", , False
End Sub
答案 0 :(得分:0)
您的CopyPriceOver
sub有一些问题,我在下面的评论中指出了它们
Sub CopyPriceOver()
Application.ScreenUpdating = False
' Number = Range("S20:S22").Value
' You're trying to assign 3 cells' values to one number!
' You should declare Number first, declaring it as an integer would quickly flag to you
' the error caused by assigning 3 cells to it. I've opted to not use the
' variable at all, since you're checking different values anyway...
' You should full qualify ranges to a specific sheet, this example uses a With block:
With ThisWorkbook.Sheets("SheetNameHere")
' Test for individual cells' values, you specified values for S20 and S21...
If .Range("S20").Value = 1 Then
' You don't need the "Call" command, see my comment after the code
Macro1
ElseIf .Range("S21").Value = 2 Then
Macro2
End If
End With
' You called ScheduleCopyPriceOver in every If condition, simply call it afterwards
ScheduleCopyPriceOver
' You disabled screen updating and never re-enabled it
Application.ScreenUpdating = True
End Sub
关于Call
命令,请参阅此SO问题:Should I use Call keyword in VB/VBA?
你对On Error Resume Next
的全部使用也会引发auto_close
中的红旗,你应该诊断并修复错误而不是隐藏错误!
答案 1 :(得分:0)
使用以下代码
this