假设我在 python v3.6 xlwings v0.11 中定义了这个 UDF,以便在 Excel 2016 上运行。
import xlwings as xw
@xw.func
def random_val(x):
import random
return random.random()*x
UDF导入到支持xlwings的Excel表中。我已经测试过单元格 A1 中的公式 =random_val(2)
工作正常。
我的问题是如何以 1 分钟的固定时间间隔运行此 UDF,以便每分钟在单元格 A1 处刷新输出。
最佳答案
这可能不是您所期望的,但它会按您希望的方式工作。
因此,假设您的函数像这样在 HH:MM:SS 中打印时间:
Public Function MyTimeMinutesSeconds() As String
Application.Volatile
MyTimeMinutesSeconds = Format(Hour(Now), "00") & ":" & _
Format(Minute(Now), "00") & ":" & _
Format(Second(Now), "00")
End Function
因此,如果您每 N
秒重新计算一次工作表,那么该函数将每 N
秒调用一次并进行更新。这是这样调用它的方法:
Option Explicit
Public Declare Sub Sleep Lib "kernel32" (ByVal dwMilliseconds As Long)
Public Sub Starting()
Dim i As Long: i = 1
[a1].Formula = "=MyTimeMinutesSeconds()"
While i < 6
Sleep (500)
Calculate
i = i + 1
Wend
End Sub
您得到的是一个漂亮的 excel 滴答时钟:
诀窍在于函数的 Application.Volatile
部分:
A volatile function每当在工作表上的任何单元格中进行计算时,都必须重新计算。非 volatile 函数仅在输入变量发生变化时才重新计算。如果此方法不在用于计算工作表单元格的用户定义函数内,则该方法无效。
关于python - 在Excel上获取python XLwings用户定义函数以定期运行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46088382/