用VBA写一个代码,在指定位置新建一个Excel表,然后依次打开指定文件夹中每一个Excel表,依次读取表格中25家银行对应日期的收盘价,在新建的Excel表中对应生成25个sheet,每个sheet以银行命名,将每一家银行日期和当天的收盘价整理到对应的sheet中,最后保存。
时间: 2023-12-17 17:05:35 浏览: 137
以下是用VBA实现您要求的代码:
```
Sub ReadExcelFiles()
Dim wb As Workbook
Dim ws As Worksheet
Dim path As String
Dim filename As String
Dim bankname As String
Dim datecol As Long
Dim closecol As Long
Dim lastrow As Long
Dim i As Long
'设置要读取的文件夹路径
path = "C:\Path\To\Excel\Files\"
'新建一个Excel表
Set wb = Workbooks.Add
wb.SaveAs Filename:="C:\Path\To\New\Excel\File.xlsx"
'循环读取文件夹中的Excel表格
filename = Dir(path & "*.xlsx")
Do While filename <> ""
'打开Excel表格
Workbooks.Open (path & filename)
Set ws = ActiveSheet
'获取银行名称
bankname = Replace(filename, ".xlsx", "")
'在新建的Excel表格中新建一个sheet,并以银行名称命名
wb.Sheets.Add after:=wb.Sheets(wb.Sheets.Count)
ActiveSheet.Name = bankname
'查找日期和收盘价所在列
datecol = 0
closecol = 0
For i = 1 To 50 '假设日期和收盘价在前50列中
If ws.Cells(1, i).Value = "日期" Then
datecol = i
End If
If ws.Cells(1, i).Value = "收盘价" Then
closecol = i
End If
Next i
'将日期和收盘价整理到新建的sheet中
lastrow = ws.Cells(ws.Rows.Count, datecol).End(xlUp).Row
For i = 2 To lastrow '假设第一行为表头
wb.Sheets(bankname).Cells(i - 1, 1).Value = ws.Cells(i, datecol).Value
wb.Sheets(bankname).Cells(i - 1, 2).Value = ws.Cells(i, closecol).Value
Next i
'关闭Excel表格
Workbooks(filename).Close
'继续循环读取下一个Excel表格
filename = Dir
Loop
'保存新建的Excel表格
wb.Save
wb.Close
End Sub
```
请将代码中的路径改为实际的路径,并根据实际情况修改其他参数。注意,该代码假设每个Excel表格的第一行为表头。
阅读全文