我要求客户端要求我们从同一目录中存在的多个Excel工作表中重命名该列。 有70多个excel报告,我们不确定特定列是否存在于哪个excel文件中。因此,每当他们要求我们改变时,我们总是需要深入查看所有excel表格,以找出所需的更改,这非常耗时。
我想过自动化这个过程。由于所有文件都存在于同一目录下,因此我们不能使用MACRO,BATCH / UNIX SCRIPTS或任何其他方式来遍历整个目录并通过执行查找和替换来进行更改。
所以我的第一个问题是,如果可行的话?如果是,那么任何人都可以建议/建议如何解决这个过程吗?
先谢谢
答案 0 :(得分:0)
我不能完全赞同以下内容,因为这是我多年来使用的拼凑而成的代码。这就是我亲自去做的事情:
下面的示例循环遍历每个Excel文件,并在将单元格“A1”更改为“Hello World”后将其从“待办事项”文件夹移动到“完成”文件夹。当“待办事项”文件夹为空时,代码将停止。
您需要更改文件路径才能生效。
Sub Example()
Dim FolderPath As String, FilePath As String, FileCount As Integer
Dim objExcelApp As Object
Dim wb As Object
Dim SaveName As String
FolderPath = "C:\Users\********\Desktop\To Do\"
NewFolderPath = "C:\Users\********\Desktop\Done\"
FilePath = FolderPath & "*.xl??"
FileName = Dir(FilePath)
ChangeNextFile:
FileCount = 0
'count how many files in "files to be changed" folder
Do While FileName <> ""
FileCount = FileCount + 1
FileName = Dir()
Loop
'if there are no files left end the code
If FileCount = 0 Then GoTo FinishedLoadingFiles
'choose the first file to change
FileName = Dir(FilePath)
Debug.Print FileName
'create an instance of Excel
Set objExcelApp = CreateObject("Excel.Application")
With objExcelApp
.Visible = False
.DisplayAlerts = False
End With
'opens the excel file in the background
objExcelApp.Workbooks.Open FileName:=FolderPath & FileName, UpdateLinks:=False
Set wb = objExcelApp.ActiveWorkbook
objExcelApp.ActiveWindow.Activate
'changes cell "A1" to say "hellow world"
wb.Sheets(1).Cells(1, 1).Value = "Hello World"
'saves the file in the done pile
wb.saveas NewFolderPath & FileName '& ".xlsb"
'closes excel
With objExcelApp
.DisplayAlerts = True
End With
wb.Close
objExcelApp.Quit
Set wb = Nothing
Set objExcelApp = Nothing
'deletes the original file. New file has been saved in the new folder
Kill FolderPath & FileName
GoTo ChangeNextFile
FinishedLoadingFiles:
MsgBox "All done"
End Sub