我需要运行一千个 excel 文件 (.xlsx) 来获取数据。每个文件有很多张表,在每张表中,单元格A1包含一个Excel插件(Morningstar Excel add-in)的功能。现在,我必须手动打开每个文件。当加载项加载时,单元格 A1 中的函数被执行并且单元格 A1 显示“处理中...”。我必须等待几秒钟或几分钟才能返回数据。表格填满数据后,我会将其保存为 csv 文件。
我如何自动化这个过程?
我编写了一个宏来打开 excel 文件并将工作表另存为 CSV 文件。但是,它绕过了数据请求和下载过程。我添加了等待几秒钟的选项,但 Excel 文件以冻结状态打开,即未加载加载项并且单元格 A1 中的函数未运行。我怎样才能:
- 打开文件
- 确保加载项已加载
- 确保每张工作表的单元格 A1 中的函数运行
- 检查是否有任何数据。一种方法是检查单元格 A10 是否为空
- 将工作表另存为 CSV 文件
到目前为止,这是我的代码:
Sub morningstar_VBA()
'PURPOSE: To loop through all Excel files in a user specified folder and perform a set task on them
Dim wb As Workbook
Dim myPath As String
Dim myFile As String
Dim myExtension As String
Dim filename As String
Dim path_to_save As String
Dim FldrPicker As FileDialog
Dim w As Long
'Retrieve Target Folder Path From User
Set FldrPicker = Application.FileDialog(msoFileDialogFolderPicker)
With FldrPicker
.Title = "Select A Target Folder"
.AllowMultiSelect = False
If .Show <> -1 Then GoTo NextCode
myPath = .SelectedItems(1) & "\"
End With
'In Case of Cancel
NextCode:
myPath = myPath
If myPath = "" Then GoTo ResetSettings
'Target File Extension (must include wildcard "*")
myExtension = "*.xlsx*"
'Target Path with Ending Extention
myFile = Dir(myPath & myExtension)
'Loop through each Excel file in folder
Do While myFile <> ""
'Set variable equal to opened workbook
Set wb = Workbooks.Open(filename:=myPath & myFile)
'Ensure Workbook has opened before moving on to next line of code
For w = 1 To Worksheets.Count
With Worksheets(w).Copy
'the ActiveWorkbook is now the new workbook populated with a copy of the current worksheet
With ActiveWorkbook
filename = .Worksheets(1).Name
path_to_save = "E:\Morningstar_download\test\" & filename
.SaveAs filename:=path_to_save, FileFormat:=xlCSV
DoEvents
.Close savechanges:=False
End With
End With
Next w
wb.Close savechanges:=True
'Ensure Workbook has closed before moving on to next line of code
DoEvents
'Get next file name
myFile = Dir
Loop
'Message Box when tasks are completed
MsgBox "Task Complete!"
ResetSettings:
'Reset Macro Optimization Settings
Application.EnableEvents = True
Application.Calculation = xlCalculationAutomatic
Application.ScreenUpdating = True
End Sub