定期获取 python Excel 到 运行 上的 XLwings 用户定义函数

Get python XLwings user-defined function on Excel to run at regular interval

假设我在 Excel 2016 的 python v3.6 xlwings v0.11 到 运行 中定义了这个 UDF。

import xlwings as xw

@xw.func
def random_val(x):
    import random
    return random.random()*x

UDF 被导入到支持 xlwings 的 Excel sheet 中。我已经测试过单元格 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 部分:

只要在工作表上的任何单元格中进行计算,就必须重新计算 volatile function。非易失性函数仅在输入变量发生变化时才重新计算。如果此方法不在用于计算工作表单元格的用户定义函数内,则此方法无效。

这可以通过宏轻松完成。

import xlwings as xw

@xw.sub
def my_macro():
    import time
    import random
    wb = xw.Book.caller()
    while True:
        time.sleep(60)
        wb.sheets[0].range('A1').value = random.random()

After clicking on Import Python UDFs, you can then use this macro by executing it via Alt + F8 or by binding it e.g. to a button. To to the latter, make sure you have the Developer tab selected under File > Options > Customize Ribbon. Then, under the Developer tab, you can insert a button via Insert > Form Controls. After drawing the button, you will be prompted to assign a macro to it and you can select my_macro.