思路是将SW的BOM表导入到EXCEL,然后将EXCEL的数据(零件名+数量)写入到字典,然后通过文件名来匹配到字典里存的数据(数量)写入到零件的数量属性。其中提示请输入数据时需要粘帖数据进来。Myr = 500 '需人工设定。欢迎大家进行补充、使程序更智能。7 b7 Y" H4 Y( ]: ~8 ]
: q& M# x+ D# A+ u0 ^
Sub main(): T% H+ I4 l1 \0 v
'打开EXCEL表格开始
* b! }1 v* Y! L; `Dim ExcelSheet As Object' |, c* W& {1 ?
Set ExcelSheet = CreateObject("Excel.Sheet")
$ n: f" W* j( ?* y& `8 }ExcelSheet.Application.Visible = True4 w; y" T' q/ O" Q7 j. F) g- g# q% u( |
'结束
& B! c! e8 Z* n! j! K
6 c* D, ^; R" q% P- R7 h'填入数据开始" H$ M+ z$ \: Z+ T* s u* W5 J
Dim d7 {) v( P/ G* h. {
Set d = CreateObject("Scripting.Dictionary")
# ?+ T& u8 e2 d( aMsgBox "请输入数据"
`6 T2 m6 M& [/ |9 D# H$ ]'结束- N5 X' ~' V/ V. k! `* L+ E
) Z4 w) R& a6 \) l: W
'数据写入字典开始& n3 W4 f9 g3 s
Dim Myr&; n) e* O; v( r ^ i& E
Myr = 500 '需人工设定. S* \3 V+ }1 r! l2 C- y! c7 m
For i = 1 To Myr8 M1 c" V1 r( P& I! M
d(ExcelSheet.Application.Cells(i, 1).Value) = ExcelSheet.Application.Cells(i, 2).Value
% o" @8 ~1 H3 ~# |Next
; e: ]1 m" u$ g0 r" O7 E'结束
; H( K N y/ t
: \ B% w6 H0 n0 i Q" Z% R/ K) b'将字典数据逐个写入到零件开始# \0 S4 X p9 g8 I' u* C
Dim swApp As Object) t3 c N9 ^9 [2 g) j
Dim Part As Object. a* G' p9 [1 O( u; b; N6 {
Dim longstatus As Long, longwarnings As Long
' P- u- M/ ?5 G% hDim myPath$, myFile$! \* x v& f( ?6 N) J
8 O# ~; R$ e* H* G
Set swApp = _
: l( Y1 k- w9 A% k3 K3 S" I" zApplication.SldWorks/ I( t' V k! o+ T- {
myPath = "C:\Users\Administrator\Desktop\1\" '..........................重点:把文件路径定义给变量
1 C8 w" }9 w X% jmyFile = Dir(myPath & "*.sldprt") '依次找寻指定路径中的*.文件6 T. h u3 a; L* {4 R
Do While myFile <> ""& G) {% I4 }& d* @ l( x
Set Part = swApp.OpenDoc6(myPath & myFile, 1, 0, "", longstatus, longwarnings)
4 [) Q4 D& ~# `% W6 ]9 F$ V6 L9 ^; C
) O" w0 K7 g. p& o+ p '单个零件写入数据开始( f( `: M, e) ~
'Dim swApp As Object
' t" W: R6 f6 E- X: gDim c As String
: y& v9 v& _ W; k( ?Set swApp = Application.SldWorks
6 B& Q/ W- g+ WSet Part = swApp.ActiveDoc9 v# A7 }' `8 Y: b. m7 E
c = swApp.ActiveDoc.GetTitle() '零件名
* w9 [, s: u- X. A0 ^blnretval = Part.AddCustomInfo3("", "数量", swCustomInfoText, d.Item(c))' H: A5 E" B/ m! s
'单个零件写入数据结束
! g( [2 d9 @* _+ g$ X1 L. h$ M3 k) D0 W+ K3 `% }* Q
Part.Save6 e: ?. r9 m/ z. a; `. P. Z6 W
swApp.CloseDoc myPath & myFile9 P0 f4 z' Q; n2 i* j2 s ~
myFile = Dir '找寻下一个*.文件
5 G' k! g z% z, t1 ~$ { ~Loop4 H1 t6 v/ s, r: N0 f% @* t; @) w
'将字典数据逐个写入到零件结束
& W7 M2 U) P& w p# c" k. i( k6 jEnd Sub
3 _) n/ X9 _" j |