我是 Python 新手。任何人都可以幫助如何生成自動增量,如 B00001、B00002、B00003...... 它可以使用特定檔案夾中的按鈕自動保存 excel 檔案名。
我試過了
global numXlsx
numXlsx = 1
wb.save(f'invoice/B{numXlsx}.xlsx')
numXlsx = 1
但是當我用不同的資料點擊按鈕幾次時,它仍然會覆寫 B1.xlsx 檔案。任何人都可以幫助解決這個問題:)
uj5u.com熱心網友回復:
聽起來您遇到的最大問題是每次單擊按鈕都會重新開始執行 python 腳本,因此使用全域變數將不起作用,因為它不會在執行程序中持續存在。在這種情況下,我建議在每次執行腳本時使用pickle 模塊之類的東西來存盤和重新加載計數器值。使用該模塊,您的解決方案可能如下所示:
import pickle
from pathlib import Path
# creates file if it doesn't exist
myfile = Path("save.p")
myfile.touch(exist_ok=True)
persisted = {}
with (open(myfile, "rb")) as f:
try:
persisted = pickle.load(f)
except EOFError:
print("file was empty, nothing to load")
# use get() to avoid KeyError if key doesn't exist
if persisted.get('counter') is None:
persisted['counter'] = 1
wb.save(f"invoice/B{persisted.get('counter')}.xlsx")
persisted['counter'] = 1
# save everything back into the same file to be used next execution
pickle.dump(persisted, open(myfile, "wb"))
獎勵:如果您希望在檔案名中用零填充計數,請persisted.get('counter'):05d在保存檔案時使用大括號。表示您希望結果5值至少為 5 個字符長,例如2將變為00002并且111將變為00111。
uj5u.com熱心網友回復:
您可以嘗試使用全域變數并每次都增加它。嘗試使用類似的東西:(將其初始化為 0)
global numXlsx # this is like your counter variable)
wb.save(f'folder/B{numXlsx}.xlsx')
numXlsx = 1 # Incrementing the variable so it does not overwrite the file as your code is doing
祝你今天過得愉快!
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/439941.html
上一篇:如果找不到多個搜索字串,則洗掉行
下一篇:VBA優化陣列決議和匹配字串
