我已经创建了一对可重用的子例程,它们一起工作以保存不同扩展名中的文件。创建通用参考表:是一个正确的方法吗?
第一个Sub接收目录路径,文件名和所需的Excel扩展名。然后,它调用第二次找到了正确的Excel的FileFormat号并用它来将文件保存在新的格式:
Sub SaveFileWithNewExtension(DirectoryPath As String, NameOfFile As String, ExtensionToUse As String)
Dim ExcelFileFormatNumber As String
GetExcelFormatNumber ExtensionToUse, ExcelFileFormatNumber
ActiveWorkbook.SaveAs DirectoryPath & "\" & NameOfFile & ExtensionToUse, FileFormat:=ExcelFileFormatNumber
End Sub
第二次主要是为Excel FileFormats我会用一个参考。对于参考的FileFormat我同时存储在的FileFormat号码和名称中键入到不同的文件扩展的阵列中,所有存储在一个集合,我可以添加到根据需要:
Sub GetExcelFormatNumber(Extension As String, Optional Number As String, Optional ExcelFormat As String)
'http://msdn.microsoft.com/en-us/library/office/ff198017.aspx
'http://www.rondebruin.nl/mac/mac020.htm
Dim ExtensionReference As New Collection
ExtensionReference.Add Array("51", "xlOpenXMLWorkbook"), ".xlsx"
ExtensionReference.Add Array("52", "xlOpenXMLWorkbookMacroEnabled"), ".xlsm"
ExtensionReference.Add Array("50", "xlExcel12"), ".xlsb"
ExtensionReference.Add Array("56", "xlExcel8"), ".xls"
On Error GoTo NoMatch:
ExcelFormat = ExtensionReference.Item(Extension)(1)
Number = ExtensionReference.Item(Extension)(0)
Exit Sub
NoMatch:
msgbox "No Matching Extension was Found in the ExcelExtensionsAndNumbers Collection"
End Sub
保持数组这样的集合看起来相当笨重和不雅,这让我觉得我已经做到了这一点。
这里是我的问题: 有没有更好的方式来存储信息,以供其他潜艇使用?或者采用另一种方式表达:您是否有一种最喜欢的数据抽象方式(如本示例中的FileFormat代码),因此可以反复使用它,而无需每次都记住和重写它?
代码进行了修订,使用情况,而不是一个集合,以更好地处理错误(由代码亚洲时报Siddharth溃败的重写轻轻建议)。这工作,和案例结构使我的眼睛更有意义:
Public Sub SaveFileWithNewExtension(DirectoryPath As String, NameOfFile As String, ExtensionToUse As String)
Dim ExcelFileFormatNumber As String
GetExcelFormatNumber ExtensionToUse, ExcelFileFormatNumber
If ExcelFileFormatNumber <> "" Then
ActiveWorkbook.SaveAs DirectoryPath & "\" & NameOfFile & ExtensionToUse, FileFormat:=ExcelFileFormatNumber
Else
msgbox "Invalid file extension. Case does not exist."
End If
End Sub
Public Sub GetExcelFormatNumber(ExtensionToFind As String, Optional Number As String, Optional ExcelFormat As String)
'reference - http://msdn.microsoft.com/en-us/library/office/ff198017.aspx
'reference - http://www.rondebruin.nl/mac/mac020.htm
Select Case ExtensionToFind
Case ".xlsx": Number = "51"
ExcelFormat = "xlOpenXMLWorkbook"
Case ".xlsm": Number = "52"
ExcelFormat = "xlOpenXMLWorkbookMacroEnabled"
Case ".xlsb": Number = "50"
ExcelFormat = "xlExcel12"
Case ".xls": Number = "56"
ExcelFormat = "xlExcel8"
Case ".csv": Number = "6"
ExcelFormat = "xlCSV"
Case Else: Number = ""
ExcelFormat = ""
End Select
End Sub
您的方式是正确的。看看http://stackoverflow.com/questions/9178177以通过类实例替换这些数组。 –
@amadeus:谢谢!我一直在想关于类对象,现在看起来是我开始学习的机会。我显然必须稍微学习一下如何调用类对象,但是一旦我做了,它似乎会更好。 –