Implement a comprehensive VBA testing framework that provides precise line-by-line error reporting through code weaving technology. Core Features: - CodeWeaver: Injects line number labels and error handling into VBA code - LoggerInjector: Manages TestLogger module for capturing test results - TestRunner: Orchestrates Excel lifecycle and test execution - Command-line interface supporting single and batch testing Key Capabilities: - Captures exact line numbers where errors occur - Displays source code context for error locations - Non-invasive testing (original files unchanged) - Batch testing support with detailed summaries Components: - vba_test_runner.py: Main framework implementation - demo.xlsm: Demo Excel file with test procedures - create_demo.py: Script to generate demo files - check_vba_access.py: VBA access permission checker Co-Authored-By: Claude Sonnet 4.5 <noreply@anthropic.com>
84 lines
1.7 KiB
Python
84 lines
1.7 KiB
Python
"""
|
|
创建演示用的 Excel 文件,包含测试用的 VBA 代码
|
|
"""
|
|
|
|
import xlwings as xw
|
|
|
|
# VBA 测试代码
|
|
VBA_TEST_CODE = """Option Explicit
|
|
|
|
Sub TestErrorProcedure()
|
|
Dim x As Integer
|
|
Dim y As Integer
|
|
Dim result As Double
|
|
|
|
x = 10
|
|
y = 0
|
|
result = x / y ' 这里会触发除以零错误
|
|
|
|
Debug.Print "Result: " & result
|
|
End Sub
|
|
|
|
Sub TestTypeMismatch()
|
|
Dim x As String
|
|
Dim y As Integer
|
|
|
|
x = "Hello"
|
|
y = x ' 这里会触发类型不匹配错误
|
|
|
|
Debug.Print "Y: " & y
|
|
End Sub
|
|
|
|
Sub TestSubscriptError()
|
|
Dim arr(1 To 3) As Integer
|
|
Dim value As Integer
|
|
|
|
arr(1) = 10
|
|
arr(2) = 20
|
|
arr(3) = 30
|
|
value = arr(5) ' 这里会触发下标越界错误
|
|
|
|
Debug.Print "Value: " & value
|
|
End Sub
|
|
|
|
Sub TestSuccessfulProcedure()
|
|
Dim x As Integer
|
|
Dim y As Integer
|
|
Dim sum As Integer
|
|
|
|
x = 10
|
|
y = 20
|
|
sum = x + y
|
|
|
|
Debug.Print "Sum: " & sum
|
|
End Sub
|
|
"""
|
|
|
|
def create_demo_file():
|
|
"""创建演示用的 Excel 文件"""
|
|
app = xw.App(visible=True)
|
|
wb = app.books.add()
|
|
|
|
# 添加 VBA 模块
|
|
vba_project = wb.api.VBProject
|
|
module = vba_project.VBComponents.Add(1) # 1 = vbext_ct_StdModule
|
|
module.Name = "Module1"
|
|
module.CodeModule.AddFromString(VBA_TEST_CODE)
|
|
|
|
# 保存文件
|
|
file_path = r"D:\python\xlwings\demo.xlsm"
|
|
wb.save(file_path)
|
|
wb.close()
|
|
|
|
print(f"演示文件已创建: {file_path}")
|
|
print("\n包含的测试过程:")
|
|
print(" - TestErrorProcedure: 除以零错误")
|
|
print(" - TestTypeMismatch: 类型不匹配错误")
|
|
print(" - TestSubscriptError: 下标越界错误")
|
|
print(" - TestSuccessfulProcedure: 成功执行的测试")
|
|
|
|
app.quit()
|
|
|
|
if __name__ == "__main__":
|
|
create_demo_file()
|