引用单元格时出错-需要常量表达式



我想做什么?

代码的第3行有一个时间值(30秒),用于在一定时间后重复宏,但我无论如何都在寻找,而不是在代码中写30秒,我想在表RecordF2单元格中写30或任何东西,每次我想从那里改变时间值。

我尝试过的解决方案

我用下面的

替换了第三行代码
Public Const cRunIntervalSeconds =ThisWorkbook.Worksheets("Record").Range("F2").Value
' run my code every 30 seconds or whenever I want from the F2 cell

然后我也得到了一个错误,所以我试图使用("$F$2")而不是("F2"),但仍然没有解决。我是新的VBA,但相信一些简单的事情是在它背后,我错过了。

即将到来的问题!

行不。3给了我一个错误,.Value被高亮显示为

编译错误:Constant Expression Required

下面是代码

Option Explicit
Public RunWhen As Double
Public Const cRunIntervalSeconds = ThisWorkbook.Worksheets("Record").Range("F2").Value    ' time value in Seconds to run a macro from F2 cell
' When I use the below code in the place of 3rd line, it works fine but I need to control it from F2 cell
' Public Const cRunIntervalSeconds = 30
Public Const cRunWhat = "The_master" ' the name of the procedure to run
Dim FirstTime As Boolean

Sub StartTimer()
Set cRunIntervalSeconds = ThisWorkbook.Worksheets("Record").Range("F2").Value
If FirstTime Then
'change for today + 9:00 AM
RunWhen = Date + TimeSerial(8, 55, 0)
Else
RunWhen = Now + TimeSerial(0, 0, cRunIntervalSeconds)
End If
Application.OnTime EarliestTime:=RunWhen, _
Procedure:=cRunWhat, Schedule:=True
End Sub
Sub The_master()
Call Macro2
' Call StartTimer to run macro again
If Time > TimeSerial(12, 0, 0) Then
'do nothing
Else
StartTimer
End If
End Sub

Sub StopTimer()
'useful for testing to stop any scheduled macro
On Error Resume Next
Application.OnTime EarliestTime:=RunWhen, _
Procedure:=cRunWhat, Schedule:=False
End Sub

Sub Auto_Open()
FirstTime = True
'Change for 9:00 AM
If Time > TimeSerial(8, 55, 0) Then
FirstTime = False
End If
Call StartTimer
FirstTime = False
End Sub

我的完整代码有点复杂,它在上午9点开始一个宏,然后每30秒重复一次,直到下午2点。

使用Const语句声明一个常量。

声明常量用于代替文字值。

如果你想让它是可变的(例如:一个变量单元格值,那么你需要声明一个变量而不是一个常量!

声明一个变量

Public RunIntervalSeconds As Long

并初始化它,例如在Workbook_OpenRecord工作表的Worksheet_Change事件中:

RunIntervalSeconds = ThisWorkbook.Worksheets("Record").Range("F2").Value

在你为变量设置/初始化一个值之后,你可以在任何模块中使用它。


或者您可以使用function来返回单元格F2的值。如果您希望避免每次使用该函数时都重复从单元格中读取值,则可以使用Static变量,以便仅在第一次使用时读取该值:

Public Function RunIntervalSeconds(Optional ByVal ForceRefresh As Boolean = False) As Long
Static CellValue As Long  ' this variable will keep the value because it is static
If CellValue = 0 Or ForceRefresh Then  ' if the variable was not initialized yet read 
' read the value from the cell
CellValue = ThisWorkbook.Worksheets("Record").Range("F2").Value
End If
' and return it from the function
RunIntervalSeconds = CellValue 
End Function

这个函数可以用来代替公共变量。

你可以像RunIntervalSeconds一样使用它,它将使用第一次调用时从单元格中读取的值,或者你可以使用RunIntervalSeconds(ForceRefresh:=True)来刷新单元格中的值。

最新更新