无法使用宏保存Excel文件

时间:2014-12-10 10:16:21

标签: excel vba excel-vba

我有一个可以在Word文档上完美运行的宏,但是当我尝试在Excel中使用它时会崩溃。此宏使用PHP文件保存当前打开的文件。 PHP文件分析文档的全名并将其上载到特定文件夹。代码如下所示:

VB

Const BaseUrl = "http://localhost/docxgen-master/upload.php"

Sub SaveCopyAs(SaveAsPath)
    Const lCancelled_c As Long = 0  
    If VBA.LenB(SaveAsPath) = lCancelled_c Then Exit Sub
    ActiveDocument.Save
    Application.Documents.Add ActiveDocument.FullName
    ActiveDocument.SaveAs SaveAsPath, wdFormatXMLDocumentMacroEnabled
    ActiveDocument.Close
End Sub

Sub Macros1()
    FileName = ActiveDocument.FullName + "temp"    
    SaveCopyAs FileName   
    MsgBox WinHTTPPostRequest(BaseUrl, FileName, ActiveDocument.Name)
End Sub

'Other subroutines like WinHTTPPostRequest etc

PHP :upload.php

$fileInfo = current($_FILES);
if (!$fileInfo) die;
$target_path = "./templates/";
$pattern = '|_\d+|';
preg_match_all($pattern,$fileInfo['name'], $matches);
$target_path =  $target_path."report_0".$matches[0][1].$matches[0][2].$matches[0][3].".docm";   
if(!move_uploaded_file($fileInfo['tmp_name'], $target_path)) die;
echo "You saved it!";

如果在doc文件中使用此代码,则该代码可以正常工作。我试图在Excel中使用它,但无济于事。当然,我对代码做了一些小修改:

Sub SaveCopyAs(SaveAsPath)
    Const lCancelled_c As Long = 0  
    If VBA.LenB(SaveAsPath) = lCancelled_c Then Exit Sub
    ActiveWorkbook.Save
    Application.Workbooks.Add ActiveWorkbook.FullName
    ActiveWorkbook.SaveAs SaveAsPath, wdFormatXMLDocumentMacroEnabled
    ActiveWorkbook.Close
End Sub

但是,它不起作用。

修改

现在,我的代码如下所示:

Sub SaveCopyAs(SaveAsPath)
    Const lCancelled_c As Long = 0
    If VBA.LenB(SaveAsPath) = lCancelled_c Then Exit Sub
    ActiveWorkbook.Save
    Workbooks.Add
    ActiveWorkbook.SaveAs SaveAsPath, xlOpenXMLWorkbookMacroEnabled
    ActiveWorkbook.Close
End Sub

现在几乎可以了!它保存了文档,但遗憾的是没有宏。

修改

我的最终版本代码如下:

Sub SaveCopyAs(SaveAsPath)
    Const lCancelled_c As Long = 0
    ActiveWorkbook.Save
    Workbooks.Add ActiveWorkbook.FullName
    ActiveWorkbook.SaveAs SaveAsPath, xlOpenXMLWorkbookMacroEnabled
    ActiveWorkbook.Close
End Sub

但调试器抛出错误,指向ActiveWorkbook.Save(错误消息是俄语,所以我不知道正确的解释,但它是关于VB和宏)

修改

这是GetFile函数,当我尝试保存文档的简化代码时会引发错误:

Function GetFile(FileName)
  Dim Stream: Set Stream = CreateObject("ADODB.Stream")
  Stream.Type = 1 'Binary
  Stream.Open
  Stream.LoadFromFile FileName ' The debugger points to this line now (firts test case of code)
  GetFile = Stream.Read
  Stream.Close
End Function

1 个答案:

答案 0 :(得分:1)

我建议你使用它:

Sub SaveCopyAs(SaveAsPath)
    Const lCancelled_c As Long = 0
    Application.DisplayAlerts = False
    ActiveWorkbook.SaveAs SaveAsPath, xlOpenXMLWorkbookMacroEnabled
    Application.DisplayAlerts = True
    ActiveWorkbook.Close
End Sub

Sub SaveCopyAs(SaveAsPath)
    Const lCancelled_c As Long = 0
    Application.DisplayAlerts = False
    ActiveWorkbook.SaveCopyAs SaveAsPath
    Application.DisplayAlerts = True
    ActiveWorkbook.Close
End Sub

后者不允许您更改文件格式。