|
[广告] VBA代码宝 - VBA编程加强工具 · VBA代码随查随用 · 内置多项VBA编程加强工具 ★ 免费下载 ★ ★ 使用手册★
本帖最后由 f22cdefeh 于 2018-7-19 10:16 编辑
因研究并发需要,复制多份带宏的EXCEL文件
尝试用 VBS 调用 application.workbooks.open 来打开每个excel文件中的宏。
最后用WScript.Shell来 run 脚本 的时候,脚本先是提示“服务器发生意外情况”,过段时间后再提示“现在可以编辑XX文件”这个错误的发生是随机的,例如run30个脚本,会随机出N<30个意外。
感觉像是 Excel.Workbooks对象处理不过来open方法。
请问何解。
代码如下:
- '生成一个n长度随机字符串
- Private Function CreateRandomStr(n As Variant)
- sn = ""
- For i = 1 To n
- Randomize
- sn = sn + Chr(IIf(10 * Rnd > 5, Int(26 * Rnd + 65), Int(26 * Rnd + 97)))
- CreateRandomStr = sn
- Next i
- End Function
- '在桌面生成指定名称的目录
- Private Function GetFolderName(strTargetName)
- foldername = strTargetName
- foldername = foldername & Format(Date, "yyyymmdd") & Format(Time, "hhmmss")
- foldername = Environ("userprofile") & "\Desktop" & foldername & ""
- If Dir(foldername, vbDirectory) = "" Then '如果文件不存在
- MkDir foldername
- End If
- GetFolderName = foldername
- End Function
- Sub test(name)
- MsgBox name
- End Sub
- Sub 多线程测试()
- Dim testdir
- Dim filename
- Dim strvbs
- Dim strvbsfilename
- Dim cs
-
- cs = 30
- Set filename = CreateObject("Scripting.Dictionary")
- Set strvbsfilename = CreateObject("Scripting.Dictionary")
- testdir = GetFolderName("\多线程测试")
- For i = 1 To cs
- filename(i) = CreateRandomStr(10) & ".xlsm"
- ThisWorkbook.SaveCopyAs (testdir & filename(i))
- Do
- Loop While Dir(testdir & filename(i)) = Empty
- Next i
- For i = 1 To cs
- strvbsfilename(i) = testdir & CreateRandomStr(5) & ".vbs"
- Next i
-
- For i = 1 To cs
- strvbs = "Set objExcel = CreateObject(""Excel.Application"")" & vbCrLf
- strvbs = strvbs & "Set objWorkbook = objExcel.Workbooks.Open(""" & testdir & filename(i) & """)" & vbCrLf
- strvbs = strvbs & "objExcel.Application.Visible = false" & vbCrLf
- strvbs = strvbs & "objExcel.Application.Run" & """" & filename(i) & "!test""," & """" & filename(i) & """" & vbCrLf
- strvbs = strvbs & "objExcel.ActiveWorkbook.Close" & vbCrLf
- strvbs = strvbs & "objExcel.Application.Quit" & vbCrLf
- strvbs = strvbs & "Set objWorkbook = Nothing" & vbCrLf
- strvbs = strvbs & "Set objExcel = Nothing" & vbCrLf
-
- Open strvbsfilename(i) For Output As #1
- Print #1, strvbs
- Close #1
-
-
- Next i
- For i = 1 To cs
- Set wsh = VBA.CreateObject("WScript.Shell")
- wsh.Run strvbsfilename(i)
- Set wsh = Nothing
- Next i
- End Sub
复制代码
多线程测试.rar
(17.83 KB, 下载次数: 0)
|
|