如何编写一个运行在打开的工作簿中的宏,并根据每个工作簿的内容使用特定名称保存它们。每个工作簿在工作表“Book1”中都有唯一的列标题,因此工作簿可以由单元格A1中的文本确定。如果工作簿和工作表Book1和单元格A1 =“货币”将活动工作簿保存为Y:\ risk \ CCY.csv如果单元格A1 =“兴趣”将活动工作簿保存为Y:\ risk \ IR.csv。遍历所有打开的工作簿,直到没有打开的工作簿符合标准。
答案 0 :(得分:1)
您对VBA有任何经验吗?我使用宏录制器来弄清楚如何保存。我做了以下代码并测试了它,它对我来说很好。我尝试了两次运行它,它提示我是否要覆盖该文件。但是没有内置的其他错误处理。
Sub SaveWorkbooks()
Dim WB As Workbook
Dim FileName As String, FolderPath As String
Dim SaveWorkbook As Boolean
FolderPath = "Y:\risk"
ChDir FolderPath
For Each WB In Workbooks
Select Case WB.Sheets(1).Range("A1").Value
Case Is = "Currency"
FileName = "CCY"
Case Is = "Interest"
FileName = "IR"
Case Else
FileName = ""
End Select
'Make sure it's not saving not applicable workbooks
If FileName <> "" Then SaveWorkbook = True Else SaveWorkbook = False
If SaveWorkbook = True Then
ActiveWorkbook.SaveAs FileName:=FolderPath & "\" & FileName & ".xlsx", _
FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
End If
Next WB
End Sub
答案 1 :(得分:1)
我同意,@ thecoscosh这伤害了我的眼睛。这一次我会例外。试试这个:
Sub SaveWorkbooks()
Dim workbookObj As Workbook
For Each workbookObj In Excel.Workbooks
If workbookObj.Sheets("Book1").Range("A1").Value = "whatever" Then
workbookObj.Save
workbookObj.Close
End If
Next workbookObj
'Clean up
Set workbookObj = Nothing
End Sub