Excel VBA调用Python触发"unterminated string literal"语法错误求助
问题解决
1. 直接语法错误原因
错误提示的unterminated string literal是因为路径中的未转义反斜杠:C:\\Users\\tobin\\Documents\\Python\ 最后一个反斜杠把后续的双引号转义了,导致字符串无法正常闭合。
解决路径问题的两种方式:
- 把路径中的反斜杠替换为正斜杠:
C:/Users/tobin/Documents/Python - 给最后一个反斜杠再加一个转义符:
C:\\Users\\tobin\\Documents\\Python\\
2. Python代码的其他问题(修复后才能正常运行)
你的Python代码直接沿用了VBA的写法,在xlwings中不能直接使用Selection、xlCenter这类VBA对象/常量,需要做以下修改:
修正后的Python代码
import numpy as np import xlwings as xw from xlwings.constants import HorizontalAlignment, VerticalAlignment, Pattern, ColorIndex def formatInfluencer(): # 获取当前活动工作表的选中区域 selection = xw.apps.active.selection # 设置数字格式 selection.number_format = '0' # 设置对齐方式等属性 selection.api.HorizontalAlignment = HorizontalAlignment.xlCenter selection.api.VerticalAlignment = VerticalAlignment.xlBottom selection.api.WrapText = False selection.api.Orientation = 0 selection.api.AddIndent = False selection.api.IndentLevel = 0 selection.api.ShrinkToFit = False selection.api.ReadingOrder = xw.constants.ReadingOrder.xlContext selection.api.MergeCells = False # 设置单元格内部填充 interior = selection.api.Interior interior.Pattern = Pattern.xlSolid interior.PatternColorIndex = ColorIndex.xlAutomatic interior.Color = 10092543 interior.TintAndShade = 0 interior.PatternTintAndShade = 0
关键修改点说明
- 用
xw.apps.active.selection替代VBA的Selection,获取当前选中区域 - 通过
xlwings.constants导入标准VBA常量(比如xlCenter对应HorizontalAlignment.xlCenter) - 通过
.api访问底层VBA对象属性,实现和原VBA逻辑一致的操作
3. VBA代码确认
VBA部分代码无需修改,但要确保xlwings加载项已正确安装,且Python环境路径配置无误。
内容的提问来源于stack exchange,提问作者DataDel
相关产品推荐
相关产品推荐

