query_and_export1 中的第 234 行 xw.workBook().vba.add_module(vba_code) AttributeError:模块“xlwings”没有属性“workBook”
我正在尝试对从数据库导出到 xlsx 文件的查询数据执行我的 vba 脚本。Vba 脚本的目的是将查询的数据显示为易于解释的形式。我的 vba 脚本如下 vba_代码 = ''' 子格式表() 昏暗的工作表 变暗为数据透视表 Dim pf As PivotField
Set ws = ActiveSheet
Set pt = ws.PivotTableWizard(TableDestination:=ws.Cells(1, 6), TableName:="MainPivotTable")
' Add ct_num and periode to the main table
With pt
.AddData Field:=ws.Range("A1").Column, Function:=xlSum
.AddData Field:=ws.Range("B1").Column, Function:=xlSum
.PivotFields("ct_num").Orientation = xlRowField
.PivotFields("periode").Orientation = xlRowField
End With
' Add Dl_MontantTTC to the main table
With pt.PivotFields(ws.Range("D1").Column)
.Orientation = xlDataField
.Function = xlSum
.NumberFormat = "#,##0.00"
End With
' Create a PivotTable for each year and month as a sub-table
Dim yearField As PivotField
Dim monthField As PivotField
Set yearField = pt.PivotFields("periode")
Set monthField = pt.PivotFields("periode")
yearField.Orientation = xlPageField
monthField.Orientation = xlPageField
' Set up a filter for the main table to show only the selected year
With pt.PivotFields("periode")
.Orientation = xlPageField
.Position = 1
End With
' Set up a filter for the main table to show only the selected ct_num
With pt.PivotFields("ct_num")
.Orientation = xlPageField
.Position = 2
End With
' Hide the field list
ActiveWorkbook.ShowPivotTableFieldList = False
End Sub
'''
您看到的错误消息是
AttributeError: module 'xlwings' has no attribute 'workBook'
。发生此错误的原因是 xlwings
模块没有名为 workBook
的属性或方法。
在
xlwings
中,要访问工作簿,您应该根据您的用例使用 Book
或 books
。如果你想创建一个新的工作簿,你可以使用xw.Book()
。如果您想访问现有工作簿,可以使用 xw.books['Your Workbook Name']
。
因此,导致错误的代码行:
xw.workBook().vba.add_module(vba_code)
应改为:
xw.Book().vba.add_module(vba_code)
或者如果您正在使用现有工作簿:
xw.books['Your Workbook Name'].vba.add_module(vba_code)
请将
'Your Workbook Name'
替换为您的工作簿的实际名称¹。我希望这有帮助!