使用VBA打开和保存非Excel文件

时间:2016-04-04 15:02:39

标签: excel vba excel-vba

我有文件在打开时在Excel中打开,但它们本身不是Excel文件(它们只是在打开时转换)。我希望能够将这些文件中的一些信息提取到另一个Excel工作表中,但由于它们不是Excel文件,因此我无法链接文件。

我想用VBA打开这些文件(它们将作为Excel文件打开),然后将它们保存为永久的excle文件,以便我可以随意使用它们。

要打开文件,我有以下代码:

Option Explicit

Declare Function ShellExecute Lib "shell32.dll" _
Alias "ShellExecuteA" ( _
ByVal hWnd As Long, _
ByVal lpOperation As String, _
ByVal lpFile As String, _
ByVal lpParameters As String, _
ByVal lpDirectory As String, _
ByVal nShowCmd As Long) As Long

Function OpenAnyFile(FileToOpen As String)

Call ShellExecute(0, "Open", FileToOpen & vbNullString, _
vbNullString, vbNullString, 1)

End Function

Sub OpenFile()

Call OpenAnyFile("C:\Filename")

End Sub

但我不确定如何在此代码中保存现已打开的文件。

1 个答案:

答案 0 :(得分:0)

如果您要将此代码放入Excel VBE并运行它,那么您应该能够使用SaveAs方法(记录为here)来Workbook之类的所以

Dim owb As Workbook

With Application
    .DisplayAlerts = False
    .ScreenUpdating = False
    .EnableEvents = False
End With

fname = "Filename goes here (include .extension)"
fpath = "Path goes here"

Set owb = Application.Workbooks.Open(fpath & "\" & fname)

With owb
    .SaveAs fpath & "\" & fname & ".xlsx", 51
    .Close
End With
  

根据MSDN文档保存参数

     

表达式 .SaveAs(FileName,FileFormat,Password,WriteResPassword,ReadOnlyRecommended,CreateBackup,AccessMode,ConflictResolution,AddToMru,TextCodepage,TextVisualLayout,Local)*