簡體   English   中英

使用 python 編輯包含宏和 activex 對象的 xlsm 文件

[英]Edit xlsm file containing macro and activex objects using python

最終目標是將 append 數據轉換為包含 vba 腳本和 activex 列表框的 xlsm 文件。 首選使用 python/pandas。 對於初學者,我只想打開 xlsm 文件,添加一個空工作表並再次關閉它,而 VBA 代碼由於沒有列表框而給我錯誤。

activex 列表框給我帶來了麻煩,因為它沒有“轉移”,並且 VBA 腳本在嘗試使用列表框時會產生錯誤。 VBA 代碼在運行 python 腳本后看起來還不錯,但是在設置“xLstBox”變量時會崩潰。

我可以看到但無法實施的可能修復是:

  1. 讓 python 編輯文件而不弄亂 activex 對象
  2. 如果 VBA 腳本可以生成列表框。

我的 python 代碼:

from openpyxl import load_workbook 
xlsx_path = 'excel_file.xlsm'
wb = load_workbook(filename=xlsx_path, keep_vba=True)
wb.create_sheet('sheetname')
wb.save(xlsx_path)

我在預制的 xlsm 文件中的 VBA 代碼:

Public PreviousActiveCell As Range

Private Sub Worksheet_SelectionChange(ByVal Target As Range)

Dim xSelLst As Variant, I As Integer

Set xLstBox = ActiveSheet.ListBox1

Static pPrevious As Range
Set PreviousActiveCell = pPrevious
Set pPrevious = ActiveCell

If Not Intersect(Target, Range("A2:A999999")) Is Nothing Then
    If xLstBox.Visible = False Then
        xLstBox.Visible = True
        xLstBox.Top = ActiveCell.Row * 15
        xLstBox.Left = 0
    End If
    
Else
    If xLstBox.Visible = True Then
        xLstBox.Visible = False
           
            For I = xLstBox.ListCount - 1 To 0 Step -1
                If xLstBox.Selected(I) = True Then
                xSelLst = xLstBox.List(I) & "," & xSelLst
                End If
            Next I
        
            If xSelLst <> "" Then
                PreviousActiveCell = Mid(xSelLst, 1, Len(xSelLst) - 1)
            End If
            
        For I = xLstBox.ListCount - 1 To 0 Step -1
            ListBox1.Selected(I) = False
        Next I
            
    End If

End If

End Sub

Openpyxl 不能保證管理 vba 組件,因此您可能會遇到包含這些對象的 xlsm 工作表問題。
如果您在 Windows(或者可能是 Mac)上運行並且可以使用 Xlwings,這可能會有所幫助。 Xlwings 需要在本地安裝 Excel。
例如,您的第一個測試,添加工作表不應該影響您的列表框。

import xlwings as xw

xlsx_path = 'excel_file.xlsm'

with xw.App() as app:
    wb = xw.Book(xlsx_path)
    wb.sheets.add('sheetname', after='Sheet1')

    wb.save(xlsx_path)
    wb.close()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM