以下vba打开一个excel工作簿检查它是否处于只读模式,如果它等待读/写处于活动状态然后运行代码。简单
我的问题是我有很多excel文件,例如C:\ TEST \ TEST.xlsb,C:\ TEST \ TEST2.xlsb,C:\ TEST \ TEST3.xlsb,C:\ TEST \ TEST4.xlsb等等
如何让VBA通过每个工作簿名称运行代码
为每个工作簿名称多次保存复制/粘贴代码的时间。
Function test()
Dim xl As Object
Set xl = CreateObject("Excel.Application")
xl.Workbooks.Open ("C:\TEST\Test.xlsb")
Do Until xl.ActiveWorkbook.ReadOnly = False
MsgBox ("Workbook in use, waiting till read/write is active")
Call Pause(5)
xl.Quit
xl.Workbooks.Open ("C:\TEST\Test.xlsb")
If xl.ActiveWorkbook.ReadOnly = False Then Exit Do
Loop
If xl.ActiveWorkbook.ReadOnly = False Then
MsgBox ("read/write active")
'Run code
xl.Sheets("Sheet1").Range("G2").Value = 2222
xl.ActiveWorkbook.Save
xl.Quit
End If
xl.Quit
Set xl = Nothing
End Function
答案 0 :(得分:0)
你需要一个循环来浏览你的文件并为每个文件调用该函数。 如果文件名的模式类似于C:\ TEST \ TEST.xlsb,C:\ TEST \ TEST2.xlsb,C:\ TEST \ TEST3.xlsb,C:\ TEST \ TEST4.xlsb 然后你可以实现另一个函数来建立文件名作为字符串并将其设置为你的函数“test”的参数
Function goThroughFiles()
Dim front as String
Dim ending as String
Dim i as Integer
Dim strPath as String
front = C:\TEST\TEST
ending = .xlsb
i = 1
// start with filename that has no number in it
strPath = front & ending
// check if file exists
Do Until Len(Dir(strPath)) = 0
call test(strPath)
i = i+1
strPath = front & i & ending
Loop
您需要更改原始功能,因此它接受参数:
Function test(strPath as String)
并用输入变量
替换每个使用该路径的行 xl.Workbooks.Open ("C:\TEST\Test.xlsb")
变为
xl.Workbooks.Open (strPath)