Compare commits
4 Commits
ab01835b06
...
d156fdb2d8
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
d156fdb2d8 | ||
|
|
ee1120c247 | ||
|
|
df81562dd9 | ||
|
|
788a8fd9e7 |
1
.gitignore
vendored
1
.gitignore
vendored
@@ -15,4 +15,5 @@ tmpclaude-*
|
|||||||
*.png
|
*.png
|
||||||
data/
|
data/
|
||||||
Excel/
|
Excel/
|
||||||
|
Access/
|
||||||
VBA/
|
VBA/
|
||||||
34
CLAUDE.md
34
CLAUDE.md
@@ -4,7 +4,7 @@ This file provides guidance to Claude Code (claude.ai/code) when working with co
|
|||||||
|
|
||||||
## Project Overview
|
## Project Overview
|
||||||
|
|
||||||
**Auto_BOM** is a VBA code extraction and management toolkit for Excel-based Bill of Materials (BOM) processing. The project provides Python tools to extract VBA code from `.xlsm` files, manage it externally, and import it back into Excel.
|
**Auto_BOM** is a VBA code extraction and management toolkit for Excel-based Bill of Materials (BOM) processing. The project provides Python tools to extract VBA code from `.xlsm` (Excel) and `.accdb` (Access) files, manage it externally, and import it back.
|
||||||
|
|
||||||
The VBA code implements a hierarchical BOM management system with:
|
The VBA code implements a hierarchical BOM management system with:
|
||||||
- **clsBOMManager**: Main class managing BOM data structure and category relationships
|
- **clsBOMManager**: Main class managing BOM data structure and category relationships
|
||||||
@@ -16,14 +16,15 @@ The VBA code implements a hierarchical BOM management system with:
|
|||||||
```
|
```
|
||||||
Auto_BOM/
|
Auto_BOM/
|
||||||
├── Excel/ # Source Excel files (.xlsm) - gitignored
|
├── Excel/ # Source Excel files (.xlsm) - gitignored
|
||||||
|
├── Access/ # Source Access files (.accdb) - gitignored
|
||||||
├── VBA/ # Extracted VBA code - gitignored
|
├── VBA/ # Extracted VBA code - gitignored
|
||||||
│ ├── Modules/ # Standard modules (.bas)
|
│ ├── Modules/ # Standard modules (.bas)
|
||||||
│ ├── ClassModules/ # Class modules (.cls)
|
│ ├── ClassModules/ # Class modules (.cls)
|
||||||
│ ├── DocumentModules/# Sheet/workbook modules (.cls)
|
│ ├── DocumentModules/# Sheet/workbook modules (.cls)
|
||||||
│ ├── Forms/ # User forms
|
│ ├── Forms/ # User forms
|
||||||
│ └── vba_metadata.json # Module metadata for import
|
│ └── vba_metadata.json # Module metadata for import
|
||||||
├── extract_vba.py # Extract VBA from Excel files
|
├── extract_vba.py # Extract VBA from Excel/Access files
|
||||||
├── import_vba.py # Import VBA back to Excel files
|
├── import_vba.py # Import VBA back to Excel/Access files
|
||||||
├── main.py # Empty placeholder
|
├── main.py # Empty placeholder
|
||||||
└── requirements.txt # Python dependencies
|
└── requirements.txt # Python dependencies
|
||||||
```
|
```
|
||||||
@@ -40,8 +41,8 @@ pip install -r requirements.txt
|
|||||||
```
|
```
|
||||||
|
|
||||||
**Dependencies:**
|
**Dependencies:**
|
||||||
- `pywin32>=306` - Windows COM interface for Excel automation (Windows only)
|
- `pywin32>=306` - Windows COM interface for Excel/Access automation (Windows only)
|
||||||
- `oletools>=0.60` - Alternative VBA extraction without Excel dependency
|
- `oletools>=0.60` - Alternative VBA extraction without Excel dependency (Excel only)
|
||||||
|
|
||||||
## Common Commands
|
## Common Commands
|
||||||
|
|
||||||
@@ -51,20 +52,24 @@ pip install -r requirements.txt
|
|||||||
python extract_vba.py
|
python extract_vba.py
|
||||||
```
|
```
|
||||||
|
|
||||||
Two extraction methods available:
|
**Excel (.xlsm)** - Two extraction methods available:
|
||||||
1. **COM Interface** (recommended) - Requires Microsoft Excel, more reliable
|
1. **COM Interface** (recommended) - Requires Microsoft Excel, more reliable
|
||||||
2. **olevba Library** - No Excel required, uses oletools
|
2. **olevba Library** - No Excel required, uses oletools
|
||||||
|
|
||||||
For COM method, ensure Excel trusts VBA access:
|
**Access (.accdb)** - Only COM Interface supported (requires Microsoft Access)
|
||||||
|
|
||||||
|
For COM method, ensure the application trusts VBA access:
|
||||||
- Excel > Options > Trust Center > Trust Center Settings
|
- Excel > Options > Trust Center > Trust Center Settings
|
||||||
- Check "Trust access to the VBA project object model"
|
- Check "Trust access to the VBA project object model"
|
||||||
|
|
||||||
### Import VBA Code
|
### Import VBA Code
|
||||||
```bash
|
```bash
|
||||||
# Import from VBA/ directory back to Excel
|
# Import from VBA/ directory back to Excel or Access
|
||||||
python import_vba.py VBA/vba_metadata.json
|
python import_vba.py
|
||||||
```
|
```
|
||||||
|
|
||||||
|
Set `TARGET_FILE` in `.env` to the target `.xlsm` or `.accdb` file path.
|
||||||
|
|
||||||
## VBA Code Architecture
|
## VBA Code Architecture
|
||||||
|
|
||||||
### BOM Data Model
|
### BOM Data Model
|
||||||
@@ -98,12 +103,12 @@ The VBA system implements a hierarchical category-based material management:
|
|||||||
|
|
||||||
- Cleans `Attribute` statements from exported code for readability
|
- Cleans `Attribute` statements from exported code for readability
|
||||||
- Automatically categorizes modules by type (Standard/Class/Document/Form)
|
- Automatically categorizes modules by type (Standard/Class/Document/Form)
|
||||||
- Generates `vba_metadata.json` tracking source file, module names, types, and file mappings
|
|
||||||
- Module type detection based on naming conventions (mod_=Standard, cls=Class, sheet=Document)
|
- Module type detection based on naming conventions (mod_=Standard, cls=Class, sheet=Document)
|
||||||
|
- Auto-detects file type by extension (.xlsm → Excel, .accdb → Access)
|
||||||
|
|
||||||
### VBA Import (import_vba.py)
|
### VBA Import (import_vba.py)
|
||||||
|
|
||||||
- Uses Windows COM to interact with Excel
|
- Uses Windows COM to interact with Excel or Access
|
||||||
- **Critical fix for ClassModules**: Reconstructs `VERSION 1.0 CLASS` header before import
|
- **Critical fix for ClassModules**: Reconstructs `VERSION 1.0 CLASS` header before import
|
||||||
- **Encoding handling**: Uses GB18030 for temp files to prevent Chinese character corruption
|
- **Encoding handling**: Uses GB18030 for temp files to prevent Chinese character corruption
|
||||||
- Path recognition logic handles relative/absolute paths in metadata
|
- Path recognition logic handles relative/absolute paths in metadata
|
||||||
@@ -125,15 +130,16 @@ The `.vscode/settings.json` associates `.cls` files with Visual Basic syntax hig
|
|||||||
## Platform Requirements
|
## Platform Requirements
|
||||||
|
|
||||||
- **Windows required** for import functionality (COM interface)
|
- **Windows required** for import functionality (COM interface)
|
||||||
- **Microsoft Excel** required for COM-based extraction/import
|
- **Microsoft Excel** required for Excel COM-based extraction/import
|
||||||
- Cross-platform extraction possible with oletools (no Excel needed)
|
- **Microsoft Access** required for Access COM-based extraction/import
|
||||||
|
- Cross-platform extraction possible with oletools (Excel only, no Office needed)
|
||||||
|
|
||||||
## Git Workflow
|
## Git Workflow
|
||||||
|
|
||||||
The `.gitignore` excludes:
|
The `.gitignore` excludes:
|
||||||
- Virtual environment (`.venv/`)
|
- Virtual environment (`.venv/`)
|
||||||
- Build artifacts (`build/`, `dist/`)
|
- Build artifacts (`build/`, `dist/`)
|
||||||
- Project data (`Excel/`, `VBA/`)
|
- Project data (`Excel/`, `Access/`, `VBA/`)
|
||||||
- Claude temporary files (`.claude/`, `tmpclaude-*`)
|
- Claude temporary files (`.claude/`, `tmpclaude-*`)
|
||||||
|
|
||||||
Only commit code changes, not extracted VBA or Excel files.
|
Only commit code changes, not extracted VBA or Excel files.
|
||||||
|
|||||||
205
extract_vba.py
205
extract_vba.py
@@ -1,7 +1,7 @@
|
|||||||
"""
|
"""
|
||||||
VBA代码提取工具
|
VBA代码提取工具
|
||||||
从xlsm文件中提取模块和类模块代码,分类保存到VBA文件夹
|
从Excel(.xlsm)或Access(.accdb)文件中提取VBA代码,分类保存到VBA文件夹
|
||||||
自动清理Attribute信息并生成元数据JSON文件
|
自动清理Attribute信息
|
||||||
"""
|
"""
|
||||||
|
|
||||||
import os
|
import os
|
||||||
@@ -20,7 +20,7 @@ except ImportError:
|
|||||||
|
|
||||||
# ==================== 配置区域 ====================
|
# ==================== 配置区域 ====================
|
||||||
# 从 .env 文件读取配置,如果未设置则使用 None(交互模式)
|
# 从 .env 文件读取配置,如果未设置则使用 None(交互模式)
|
||||||
TARGET_XLSM_FILE = os.getenv("TARGET_XLSM_FILE", "").strip() or None
|
TARGET_FILE = os.getenv("TARGET_FILE", "").strip() or None
|
||||||
# VBA代码输出目录(如果未设置,则使用源文件同目录下的VBA文件夹)
|
# VBA代码输出目录(如果未设置,则使用源文件同目录下的VBA文件夹)
|
||||||
VBA_OUTPUT_DIR = os.getenv("VBA_OUTPUT_DIR", "").strip() or None
|
VBA_OUTPUT_DIR = os.getenv("VBA_OUTPUT_DIR", "").strip() or None
|
||||||
# =================================================
|
# =================================================
|
||||||
@@ -31,19 +31,41 @@ CLASS_MODULE_DIR = "ClassModules"
|
|||||||
DOCUMENT_MODULE_DIR = "DocumentModules"
|
DOCUMENT_MODULE_DIR = "DocumentModules"
|
||||||
FORMS_DIR = "Forms"
|
FORMS_DIR = "Forms"
|
||||||
|
|
||||||
|
# 支持的文件类型
|
||||||
|
ACCESS_EXTENSIONS = {'.accdb', '.mdb'}
|
||||||
|
EXCEL_EXTENSIONS = {'.xlsm', '.xls', '.xlsb'}
|
||||||
|
|
||||||
|
|
||||||
|
def get_file_type(file_path: Path) -> str:
|
||||||
|
"""
|
||||||
|
根据文件扩展名判断文件类型
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
'access' 或 'excel'
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
ValueError: 不支持的文件扩展名
|
||||||
|
"""
|
||||||
|
ext = file_path.suffix.lower()
|
||||||
|
if ext in ACCESS_EXTENSIONS:
|
||||||
|
return 'access'
|
||||||
|
if ext in EXCEL_EXTENSIONS:
|
||||||
|
return 'excel'
|
||||||
|
raise ValueError(f"不支持的文件类型: {ext}(支持: .xlsm, .xls, .xlsb, .accdb, .mdb)")
|
||||||
|
|
||||||
|
|
||||||
class VBAExtractor:
|
class VBAExtractor:
|
||||||
"""VBA代码提取器"""
|
"""VBA代码提取器"""
|
||||||
|
|
||||||
def __init__(self, xlsm_path: str, output_dir: str = None):
|
def __init__(self, source_path: str, output_dir: str = None):
|
||||||
"""
|
"""
|
||||||
初始化VBA提取器
|
初始化VBA提取器
|
||||||
|
|
||||||
Args:
|
Args:
|
||||||
xlsm_path: xlsm文件路径
|
source_path: 源文件路径(支持.xlsm/.accdb等)
|
||||||
output_dir: 输出目录(如果未指定,则使用VBA_OUTPUT_DIR配置或源文件同目录)
|
output_dir: 输出目录(如果未指定,则使用VBA_OUTPUT_DIR配置或源文件同目录)
|
||||||
"""
|
"""
|
||||||
self.xlsm_path = Path(xlsm_path)
|
self.source_path = Path(source_path)
|
||||||
|
|
||||||
# 确定输出目录的优先级:
|
# 确定输出目录的优先级:
|
||||||
# 1. 参数指定的 output_dir
|
# 1. 参数指定的 output_dir
|
||||||
@@ -55,7 +77,7 @@ class VBAExtractor:
|
|||||||
self.output_dir = Path(VBA_OUTPUT_DIR)
|
self.output_dir = Path(VBA_OUTPUT_DIR)
|
||||||
else:
|
else:
|
||||||
# 使用目标文件同目录下的VBA文件夹
|
# 使用目标文件同目录下的VBA文件夹
|
||||||
self.output_dir = self.xlsm_path.parent / "VBA"
|
self.output_dir = self.source_path.parent / "VBA"
|
||||||
|
|
||||||
# 创建输出目录结构
|
# 创建输出目录结构
|
||||||
self.modules_dir = self.output_dir / STANDARD_MODULE_DIR
|
self.modules_dir = self.output_dir / STANDARD_MODULE_DIR
|
||||||
@@ -126,10 +148,10 @@ class VBAExtractor:
|
|||||||
print("请运行: pip install oletools")
|
print("请运行: pip install oletools")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
print(f"正在解析文件: {self.xlsm_path.name}")
|
print(f"正在解析文件: {self.source_path.name}")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
vba_parser = VBA_Parser(str(self.xlsm_path))
|
vba_parser = VBA_Parser(str(self.source_path))
|
||||||
|
|
||||||
if vba_parser.detect_vba_macros():
|
if vba_parser.detect_vba_macros():
|
||||||
print("发现VBA代码,开始提取...\n")
|
print("发现VBA代码,开始提取...\n")
|
||||||
@@ -168,14 +190,14 @@ class VBAExtractor:
|
|||||||
print("请运行: pip install pywin32")
|
print("请运行: pip install pywin32")
|
||||||
return False
|
return False
|
||||||
|
|
||||||
print(f"正在使用COM接口解析: {self.xlsm_path.name}")
|
print(f"正在使用COM接口解析: {self.source_path.name}")
|
||||||
|
|
||||||
try:
|
try:
|
||||||
excel = win32.Dispatch("Excel.Application")
|
excel = win32.Dispatch("Excel.Application")
|
||||||
excel.Visible = False
|
excel.Visible = False
|
||||||
excel.DisplayAlerts = False
|
excel.DisplayAlerts = False
|
||||||
|
|
||||||
workbook = excel.Workbooks.Open(str(self.xlsm_path.absolute()))
|
workbook = excel.Workbooks.Open(str(self.source_path.absolute()))
|
||||||
|
|
||||||
# 获取VBA项目
|
# 获取VBA项目
|
||||||
if not workbook.VBProject:
|
if not workbook.VBProject:
|
||||||
@@ -244,6 +266,84 @@ class VBAExtractor:
|
|||||||
pass
|
pass
|
||||||
return False
|
return False
|
||||||
|
|
||||||
|
def extract_vba_modules_access_com(self):
|
||||||
|
"""
|
||||||
|
使用COM接口从Access数据库提取VBA代码
|
||||||
|
|
||||||
|
需要: Microsoft Access + pywin32
|
||||||
|
"""
|
||||||
|
try:
|
||||||
|
import win32com.client as win32
|
||||||
|
except ImportError:
|
||||||
|
print("错误: 未安装pywin32库")
|
||||||
|
print("请运行: pip install pywin32")
|
||||||
|
return False
|
||||||
|
|
||||||
|
print(f"正在使用COM接口解析: {self.source_path.name}")
|
||||||
|
|
||||||
|
access = None
|
||||||
|
try:
|
||||||
|
access = win32.Dispatch("Access.Application")
|
||||||
|
access.Visible = False
|
||||||
|
access.OpenCurrentDatabase(str(self.source_path.absolute()))
|
||||||
|
|
||||||
|
# Access 通过 VBE 获取 VBProject
|
||||||
|
try:
|
||||||
|
vb_project = access.VBE.VBProjects(1)
|
||||||
|
except Exception:
|
||||||
|
print("错误: 无法访问VBA项目")
|
||||||
|
print("请确保: 1) Access信任中心设置'信任对VBA工程对象模型的访问'")
|
||||||
|
print(" 2) 数据库中包含VBA代码")
|
||||||
|
return False
|
||||||
|
|
||||||
|
print("开始提取VBA组件...\n")
|
||||||
|
|
||||||
|
# 遍历所有VBA组件
|
||||||
|
for component in vb_project.VBComponents:
|
||||||
|
module_name = component.Name
|
||||||
|
module_type = component.Type
|
||||||
|
|
||||||
|
# 获取代码
|
||||||
|
code_module = component.CodeModule
|
||||||
|
line_count = code_module.CountOfLines
|
||||||
|
|
||||||
|
if line_count > 0:
|
||||||
|
vba_code = code_module.Lines(1, line_count)
|
||||||
|
else:
|
||||||
|
vba_code = ""
|
||||||
|
|
||||||
|
# Access 只有标准模块(1)和类模块(2)
|
||||||
|
type_name = {
|
||||||
|
1: STANDARD_MODULE_DIR,
|
||||||
|
2: CLASS_MODULE_DIR,
|
||||||
|
}.get(module_type, STANDARD_MODULE_DIR)
|
||||||
|
|
||||||
|
self._process_module(module_name, vba_code, type_name)
|
||||||
|
|
||||||
|
print(f"\n提取完成!")
|
||||||
|
print(f"- 标准模块: {self.modules_dir}")
|
||||||
|
print(f"- 类模块: {self.class_modules_dir}")
|
||||||
|
return True
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(f"使用COM提取Access VBA代码时出错: {e}")
|
||||||
|
print("\n提示:")
|
||||||
|
print("1. 确保已安装Microsoft Access")
|
||||||
|
print("2. 打开Access -> 文件 -> 选项 -> 信任中心 -> 信任中心设置")
|
||||||
|
print("3. 勾选'信任对VBA工程对象模型的访问'")
|
||||||
|
return False
|
||||||
|
|
||||||
|
finally:
|
||||||
|
if access:
|
||||||
|
try:
|
||||||
|
access.CloseCurrentDatabase()
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
try:
|
||||||
|
access.Quit()
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
|
||||||
def _determine_module_type(self, module_name: str, stream_path: str) -> str:
|
def _determine_module_type(self, module_name: str, stream_path: str) -> str:
|
||||||
"""
|
"""
|
||||||
根据模块名称和流路径确定模块类型
|
根据模块名称和流路径确定模块类型
|
||||||
@@ -347,10 +447,10 @@ def main():
|
|||||||
print()
|
print()
|
||||||
|
|
||||||
# 检查是否配置了目标文件
|
# 检查是否配置了目标文件
|
||||||
if TARGET_XLSM_FILE and TARGET_XLSM_FILE.strip():
|
if TARGET_FILE and TARGET_FILE.strip():
|
||||||
# 使用配置的文件路径
|
# 使用配置的文件路径
|
||||||
script_dir = Path(__file__).parent
|
script_dir = Path(__file__).parent
|
||||||
target_path = Path(TARGET_XLSM_FILE)
|
target_path = Path(TARGET_FILE)
|
||||||
|
|
||||||
# 如果是相对路径,则相对于脚本所在目录
|
# 如果是相对路径,则相对于脚本所在目录
|
||||||
if not target_path.is_absolute():
|
if not target_path.is_absolute():
|
||||||
@@ -360,69 +460,74 @@ def main():
|
|||||||
print(f"错误: 配置的文件不存在: {target_path}")
|
print(f"错误: 配置的文件不存在: {target_path}")
|
||||||
return
|
return
|
||||||
|
|
||||||
if not target_path.suffix.lower() == '.xlsm':
|
file_type = get_file_type(target_path)
|
||||||
print(f"警告: 文件扩展名不是.xlsm: {target_path.name}")
|
source_file = target_path
|
||||||
|
print(f"使用配置文件: {source_file.name} ({file_type})")
|
||||||
xlsm_file = target_path
|
|
||||||
print(f"使用配置文件: {xlsm_file.name}")
|
|
||||||
print()
|
print()
|
||||||
else:
|
else:
|
||||||
# 交互模式:查找xlsm文件
|
# 交互模式:查找支持的文件
|
||||||
excel_dir = Path("Excel")
|
all_files = []
|
||||||
if not excel_dir.exists():
|
for scan_dir in [Path("Excel"), Path("Access")]:
|
||||||
print("错误: 未找到Excel文件夹")
|
if scan_dir.exists():
|
||||||
return
|
for ext in ["*.xlsm", "*.accdb", "*.mdb"]:
|
||||||
|
all_files.extend(scan_dir.glob(ext))
|
||||||
|
|
||||||
xlsm_files = list(excel_dir.glob("*.xlsm"))
|
if not all_files:
|
||||||
if not xlsm_files:
|
print("错误: 未找到.xlsm或.accdb文件(请检查Excel/或Access/文件夹)")
|
||||||
print("错误: Excel文件夹中没有xlsm文件")
|
|
||||||
return
|
return
|
||||||
|
|
||||||
# 如果有多个文件,让用户选择
|
# 如果有多个文件,让用户选择
|
||||||
if len(xlsm_files) > 1:
|
if len(all_files) > 1:
|
||||||
print("发现多个xlsm文件:")
|
print("发现多个文件:")
|
||||||
for i, f in enumerate(xlsm_files, 1):
|
for i, f in enumerate(all_files, 1):
|
||||||
print(f" {i}. {f.name}")
|
ft = get_file_type(f)
|
||||||
|
print(f" {i}. {f.name} ({ft})")
|
||||||
print()
|
print()
|
||||||
choice = input("请选择文件编号 (直接回车选择第1个): ").strip()
|
choice = input("请选择文件编号 (直接回车选择第1个): ").strip()
|
||||||
if not choice:
|
if not choice:
|
||||||
xlsm_file = xlsm_files[0]
|
source_file = all_files[0]
|
||||||
else:
|
else:
|
||||||
try:
|
try:
|
||||||
idx = int(choice) - 1
|
idx = int(choice) - 1
|
||||||
xlsm_file = xlsm_files[idx]
|
source_file = all_files[idx]
|
||||||
except:
|
except:
|
||||||
print("无效选择,使用第一个文件")
|
print("无效选择,使用第一个文件")
|
||||||
xlsm_file = xlsm_files[0]
|
source_file = all_files[0]
|
||||||
else:
|
else:
|
||||||
xlsm_file = xlsm_files[0]
|
source_file = all_files[0]
|
||||||
|
|
||||||
|
file_type = get_file_type(source_file)
|
||||||
print()
|
print()
|
||||||
print(f"选择文件: {xlsm_file.name}")
|
print(f"选择文件: {source_file.name} ({file_type})")
|
||||||
print()
|
print()
|
||||||
|
|
||||||
# 创建提取器
|
# 创建提取器
|
||||||
# 输出目录优先级: 1. .env中的VBA_OUTPUT_DIR配置 2. 源文件同目录下的VBA文件夹
|
extractor = VBAExtractor(str(source_file))
|
||||||
extractor = VBAExtractor(str(xlsm_file))
|
|
||||||
|
|
||||||
# 显示输出目录信息
|
# 显示输出目录信息
|
||||||
print(f"输出目录: {extractor.output_dir}")
|
print(f"输出目录: {extractor.output_dir}")
|
||||||
print()
|
print()
|
||||||
|
|
||||||
# 选择提取方法
|
# 根据文件类型选择提取方法
|
||||||
print("请选择提取方法:")
|
if file_type == 'access':
|
||||||
print(" 1. COM接口 (推荐 - 需要安装Excel)")
|
# Access 只支持COM方法
|
||||||
print(" 2. olevba库 (不需要Excel)")
|
print("Access文件仅支持COM接口提取...")
|
||||||
print()
|
success = extractor.extract_vba_modules_access_com()
|
||||||
|
|
||||||
method = input("请选择 (直接回车使用方法1): ").strip()
|
|
||||||
|
|
||||||
if method == "2":
|
|
||||||
print("\n使用olevba库提取...")
|
|
||||||
success = extractor.extract_vba_modules_olevba()
|
|
||||||
else:
|
else:
|
||||||
print("\n使用COM接口提取...")
|
# Excel 支持COM和olevba
|
||||||
success = extractor.extract_vba_modules_com()
|
print("请选择提取方法:")
|
||||||
|
print(" 1. COM接口 (推荐 - 需要安装Excel)")
|
||||||
|
print(" 2. olevba库 (不需要Excel)")
|
||||||
|
print()
|
||||||
|
|
||||||
|
method = input("请选择 (直接回车使用方法1): ").strip()
|
||||||
|
|
||||||
|
if method == "2":
|
||||||
|
print("\n使用olevba库提取...")
|
||||||
|
success = extractor.extract_vba_modules_olevba()
|
||||||
|
else:
|
||||||
|
print("\n使用COM接口提取...")
|
||||||
|
success = extractor.extract_vba_modules_com()
|
||||||
|
|
||||||
if success:
|
if success:
|
||||||
print("\n" + "=" * 60)
|
print("\n" + "=" * 60)
|
||||||
|
|||||||
180
import_vba.py
180
import_vba.py
@@ -27,8 +27,8 @@ except ImportError:
|
|||||||
|
|
||||||
# ==================== 配置区域 ====================
|
# ==================== 配置区域 ====================
|
||||||
# 从 .env 文件读取配置
|
# 从 .env 文件读取配置
|
||||||
# 目标 xlsm 文件路径(用于导入VBA代码)
|
# 目标文件路径(支持 .xlsm / .accdb / .mdb)
|
||||||
TARGET_XLSM_FILE = os.getenv("TARGET_XLSM_FILE", "").strip() or None
|
TARGET_FILE = os.getenv("TARGET_FILE", "").strip() or None
|
||||||
# VBA代码输出目录(如果未设置,则使用源文件同目录下的VBA文件夹)
|
# VBA代码输出目录(如果未设置,则使用源文件同目录下的VBA文件夹)
|
||||||
VBA_OUTPUT_DIR = os.getenv("VBA_OUTPUT_DIR", "").strip() or None
|
VBA_OUTPUT_DIR = os.getenv("VBA_OUTPUT_DIR", "").strip() or None
|
||||||
# =================================================
|
# =================================================
|
||||||
@@ -39,6 +39,29 @@ CLASS_MODULE_DIR = "ClassModules"
|
|||||||
DOCUMENT_MODULE_DIR = "DocumentModules"
|
DOCUMENT_MODULE_DIR = "DocumentModules"
|
||||||
FORMS_DIR = "Forms"
|
FORMS_DIR = "Forms"
|
||||||
|
|
||||||
|
# 支持的文件类型
|
||||||
|
ACCESS_EXTENSIONS = {'.accdb', '.mdb'}
|
||||||
|
EXCEL_EXTENSIONS = {'.xlsm', '.xls', '.xlsb'}
|
||||||
|
|
||||||
|
|
||||||
|
def get_file_type(file_path: Path) -> str:
|
||||||
|
"""
|
||||||
|
根据文件扩展名判断文件类型
|
||||||
|
|
||||||
|
Returns:
|
||||||
|
'access' 或 'excel'
|
||||||
|
|
||||||
|
Raises:
|
||||||
|
ValueError: 不支持的文件扩展名
|
||||||
|
"""
|
||||||
|
ext = file_path.suffix.lower()
|
||||||
|
if ext in ACCESS_EXTENSIONS:
|
||||||
|
return 'access'
|
||||||
|
if ext in EXCEL_EXTENSIONS:
|
||||||
|
return 'excel'
|
||||||
|
raise ValueError(f"不支持的文件类型: {ext}(支持: .xlsm, .xls, .xlsb, .accdb, .mdb)")
|
||||||
|
|
||||||
|
|
||||||
class VBAImporter:
|
class VBAImporter:
|
||||||
"""VBA代码导入器"""
|
"""VBA代码导入器"""
|
||||||
|
|
||||||
@@ -289,22 +312,151 @@ class VBAImporter:
|
|||||||
try: excel.Quit()
|
try: excel.Quit()
|
||||||
except: pass
|
except: pass
|
||||||
|
|
||||||
|
def import_vba_access(self):
|
||||||
|
"""使用Access COM导入VBA代码"""
|
||||||
|
if not self.target_file.exists():
|
||||||
|
print(f"错误: 找不到目标 Access 文件: {self.target_file}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
if not self.vba_dir.exists():
|
||||||
|
print(f"错误: 找不到 VBA 代码目录: {self.vba_dir}")
|
||||||
|
return False
|
||||||
|
|
||||||
|
print(f"正在打开 Access 数据库: {self.target_file.name} ...")
|
||||||
|
|
||||||
|
access = None
|
||||||
|
try:
|
||||||
|
access = win32.Dispatch("Access.Application")
|
||||||
|
access.Visible = False
|
||||||
|
access.OpenCurrentDatabase(str(self.target_file))
|
||||||
|
|
||||||
|
try:
|
||||||
|
vb_project = access.VBE.VBProjects(1)
|
||||||
|
except Exception:
|
||||||
|
print("错误: 无法访问 VBA 项目。请确保信任对 VBA 工程对象模型的访问。")
|
||||||
|
return False
|
||||||
|
|
||||||
|
print("开始导入模块...\n")
|
||||||
|
|
||||||
|
# 扫描所有模块(Access 只导入标准模块和类模块)
|
||||||
|
scan_dirs = [
|
||||||
|
(STANDARD_MODULE_DIR, ".bas"),
|
||||||
|
(CLASS_MODULE_DIR, ".cls"),
|
||||||
|
]
|
||||||
|
modules = []
|
||||||
|
for dir_name, ext in scan_dirs:
|
||||||
|
dir_path = self.vba_dir / dir_name
|
||||||
|
if not dir_path.exists():
|
||||||
|
continue
|
||||||
|
for file_path in dir_path.glob(f"*{ext}"):
|
||||||
|
modules.append({
|
||||||
|
"name": file_path.stem,
|
||||||
|
"type": dir_name,
|
||||||
|
"file_path": file_path,
|
||||||
|
"ext": ext
|
||||||
|
})
|
||||||
|
|
||||||
|
if not modules:
|
||||||
|
print("警告: 未找到任何 VBA 模块文件")
|
||||||
|
return False
|
||||||
|
|
||||||
|
temp_files_created = []
|
||||||
|
|
||||||
|
for module_info in modules:
|
||||||
|
module_name = module_info["name"]
|
||||||
|
module_type_dir = module_info["type"]
|
||||||
|
source_code_path = module_info["file_path"]
|
||||||
|
|
||||||
|
component = None
|
||||||
|
try:
|
||||||
|
component = vb_project.VBComponents(module_name)
|
||||||
|
except:
|
||||||
|
component = None
|
||||||
|
|
||||||
|
# 移除已存在的组件
|
||||||
|
if component:
|
||||||
|
try:
|
||||||
|
vb_project.VBComponents.Remove(component)
|
||||||
|
except Exception as e:
|
||||||
|
print(f" [警告] 无法移除 {module_name}: {e},将尝试更新代码")
|
||||||
|
# 回退到字符串注入
|
||||||
|
try:
|
||||||
|
code_module = component.CodeModule
|
||||||
|
num_lines = code_module.CountOfLines
|
||||||
|
if num_lines > 0:
|
||||||
|
code_module.DeleteLines(1, num_lines)
|
||||||
|
with open(source_code_path, 'r', encoding='utf-8') as f:
|
||||||
|
new_code = f.read()
|
||||||
|
if new_code.strip():
|
||||||
|
code_module.AddFromString(new_code)
|
||||||
|
print(f" [更新] {module_name} ({module_type_dir}) - 代码已更新")
|
||||||
|
except Exception as e2:
|
||||||
|
print(f" [错误] 更新代码 {module_name} 失败: {e2}")
|
||||||
|
continue
|
||||||
|
|
||||||
|
# 生成临时导入文件并导入
|
||||||
|
temp_file = self._reconstruct_file_content(source_code_path, module_name, module_type_dir)
|
||||||
|
temp_files_created.append(temp_file)
|
||||||
|
|
||||||
|
try:
|
||||||
|
vb_project.VBComponents.Import(str(temp_file))
|
||||||
|
print(f" [导入] {module_name} ({module_type_dir})")
|
||||||
|
except Exception as e:
|
||||||
|
print(f" [错误] 导入 {module_name} 失败: {e}")
|
||||||
|
|
||||||
|
# 清理临时文件
|
||||||
|
for p in temp_files_created:
|
||||||
|
try:
|
||||||
|
if p.exists(): p.unlink()
|
||||||
|
except: pass
|
||||||
|
try:
|
||||||
|
temp_dir = Path(tempfile.gettempdir()) / "vba_import_temp"
|
||||||
|
if temp_dir.exists(): shutil.rmtree(temp_dir)
|
||||||
|
except: pass
|
||||||
|
|
||||||
|
print("\n正在保存...")
|
||||||
|
try:
|
||||||
|
access.DoCmd.Save()
|
||||||
|
print("已保存更改。")
|
||||||
|
except Exception as e:
|
||||||
|
print(f"保存时出错: {e}")
|
||||||
|
|
||||||
|
print(f"\n导入完成!目标文件: {self.target_file.name}")
|
||||||
|
return True
|
||||||
|
|
||||||
|
except Exception as e:
|
||||||
|
print(f"\n发生未处理的错误: {e}")
|
||||||
|
import traceback
|
||||||
|
traceback.print_exc()
|
||||||
|
return False
|
||||||
|
|
||||||
|
finally:
|
||||||
|
if access:
|
||||||
|
try:
|
||||||
|
access.CloseCurrentDatabase()
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
try:
|
||||||
|
access.Quit()
|
||||||
|
except:
|
||||||
|
pass
|
||||||
|
|
||||||
def main():
|
def main():
|
||||||
print("=" * 60)
|
print("=" * 60)
|
||||||
print("VBA代码导入工具 (V4.0 - 基于配置)")
|
print("VBA代码导入工具 (V5.0 - 支持Excel和Access)")
|
||||||
print("=" * 60)
|
print("=" * 60)
|
||||||
print()
|
print()
|
||||||
|
|
||||||
script_dir = Path(__file__).parent
|
script_dir = Path(__file__).parent
|
||||||
|
|
||||||
# 检查配置
|
# 检查配置
|
||||||
if not TARGET_XLSM_FILE:
|
if not TARGET_FILE:
|
||||||
print("错误: 未配置 TARGET_XLSM_FILE")
|
print("错误: 未配置 TARGET_FILE")
|
||||||
print("请在 .env 文件中设置目标 Excel 文件路径")
|
print("请在 .env 文件中设置目标文件路径(支持.xlsm和.accdb)")
|
||||||
return
|
return
|
||||||
|
|
||||||
# 确定目标文件路径
|
# 确定目标文件路径
|
||||||
target_path = Path(TARGET_XLSM_FILE)
|
target_path = Path(TARGET_FILE)
|
||||||
if not target_path.is_absolute():
|
if not target_path.is_absolute():
|
||||||
target_path = script_dir / target_path
|
target_path = script_dir / target_path
|
||||||
|
|
||||||
@@ -312,8 +464,7 @@ def main():
|
|||||||
print(f"错误: 配置的文件不存在: {target_path}")
|
print(f"错误: 配置的文件不存在: {target_path}")
|
||||||
return
|
return
|
||||||
|
|
||||||
if not target_path.suffix.lower() == '.xlsm':
|
file_type = get_file_type(target_path)
|
||||||
print(f"警告: 文件扩展名不是 .xlsm: {target_path.name}")
|
|
||||||
|
|
||||||
# 确定 VBA 代码目录
|
# 确定 VBA 代码目录
|
||||||
if VBA_OUTPUT_DIR:
|
if VBA_OUTPUT_DIR:
|
||||||
@@ -332,13 +483,14 @@ def main():
|
|||||||
print(" 2. 或在 .env 文件中设置 VBA_OUTPUT_DIR 指定代码目录")
|
print(" 2. 或在 .env 文件中设置 VBA_OUTPUT_DIR 指定代码目录")
|
||||||
return
|
return
|
||||||
|
|
||||||
print(f"目标 Excel 文件: {target_path.name}")
|
type_label = "Access" if file_type == "access" else "Excel"
|
||||||
|
print(f"目标文件: {target_path.name} ({type_label})")
|
||||||
print(f"VBA 代码目录: {vba_path}")
|
print(f"VBA 代码目录: {vba_path}")
|
||||||
print()
|
print()
|
||||||
|
|
||||||
# 确认操作
|
# 确认操作
|
||||||
print("=" * 60)
|
print("=" * 60)
|
||||||
print("警告: 此操作将覆盖目标 Excel 文件中的 VBA 代码。")
|
print(f"警告: 此操作将覆盖目标{type_label}文件中的 VBA 代码。")
|
||||||
choice = input("\n确认继续? (y/n): ").lower().strip()
|
choice = input("\n确认继续? (y/n): ").lower().strip()
|
||||||
|
|
||||||
if choice != 'y':
|
if choice != 'y':
|
||||||
@@ -354,7 +506,11 @@ def main():
|
|||||||
print("=" * 60)
|
print("=" * 60)
|
||||||
print()
|
print()
|
||||||
|
|
||||||
success = importer.import_vba()
|
# 根据文件类型选择导入方法
|
||||||
|
if file_type == 'access':
|
||||||
|
success = importer.import_vba_access()
|
||||||
|
else:
|
||||||
|
success = importer.import_vba()
|
||||||
|
|
||||||
print()
|
print()
|
||||||
print("=" * 60)
|
print("=" * 60)
|
||||||
|
|||||||
Reference in New Issue
Block a user