【发布时间】:2013-09-28 04:38:49
【问题描述】:
我创建了一对可重用的子例程,它们一起工作以根据需要以不同的扩展名保存文件。
第一个 Sub 接收目录路径、文件名和所需的 Excel 扩展名。然后它调用第二个 Sub 以找到正确的 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 文件格式的参考。对于 FileFormat 参考,我将 FileFormat Number 和 Name 都存储在一个数组中,这些数组键入了不同的文件扩展名,所有这些都存储在一个集合中,我可以根据需要添加到其中:
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 Rout 对代码的重写所暗示的那样)。这行得通,并且案例结构对我来说更有意义:
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
【问题讨论】:
-
你是在正确的方式。查看stackoverflow.com/questions/9178177 以用类实例替换这些数组。
-
@amadeus:谢谢!我一直想知道类对象,看来现在是我开始学习的机会了。显然,我将不得不稍微玩一下类的东西来学习如何调用类对象,但似乎一旦我这样做会更好。