如果有新版本,则在打开时更新excel文件

时间:2018-04-09 13:24:16

标签: vba excel-vba excel

我有一个Excel文件,它使用数据库中的当前版本检查其本地版本。检查版本的代码对问题并不重要。

如果有新版本我想下载它,请关闭旧文件(因为我无法在打开时更改/修改它),将其替换为新下载的版本并打开下载的版本。

我所拥有的是这样的:

file.xlsm

Private Sub Workbook_Open()
  Workbooks.Open ThisWorkbook.Path & "\update.xlsm"
End Sub

update.xlsm

Private Sub Workbook_Open()
  Workbooks("file.xlsm").Close
  Dim num As Byte
  Dim WHTTP As Object
  On Error Resume Next
  Set WHTTP = CreateObject("WinHTTPrequest.5")
  If Err.Number <> 0 Then Set WHTTP = CreateObject("WinHTTPrequest.5.1")
  On Error GoTo 0
  WHTTP.Open "GET", "http://path/file.xlsm", False
  WHTTP.Send
  num = FreeFile
  On Error Resume Next
  Open ThisWorkbook.Path & "\file.xlsm" For Binary Access Write As num
  If Err.Number <> 0 Then
    Workbooks(ThisWorkbook.Path & "\file.xlsm").Close
    Open ThisWorkbook.Path & "\File.xlsm" For Binary Access Write As num
  End If
  On Error GoTo 0
  Put num, , WHTTP.ResponseBody
  Close num
  Workbooks.Open ThisWorkbook.Path & "\file.xlsm"
  ThisWorkbook.Close
End Sub

问题是,由于update.xlsm是从file.xlsm打开的,所以当我关闭file.xlsm后,update.xlsm的代码就会停止运行。

我发现this thread这就是我想做的事情,但我无法弄清楚如何让Application.OnTime正常工作。

Here我在那里获得了下载文件的代码。

编辑:

好的,所以我几乎完全使用了以下内容:

服务器file.xlsm

Private Sub Workbook_Open()
  'Workbooks.Open ThisWorkbook.Path & "\update.xlsm"
End Sub

本地file.xlsm

Private Sub Workbook_Open()
  Workbooks.Open ThisWorkbook.Path & "\update.xlsm"
End Sub

本地更新.xlsm

的ThisWorkbook:

Private Sub Workbook_Open()
  Application.OnTime Now, "test"
End Sub

模块:

Sub test()
  Workbooks("file.xlsm").Close
  Dim num As Byte
  Dim WHTTP As Object
  On Error Resume Next
  Set WHTTP = CreateObject("WinHTTPrequest.5")
  If Err.Number <> 0 Then Set WHTTP = CreateObject("WinHTTPrequest.5.1")
  On Error GoTo 0
  WHTTP.Open "GET", "http://path/file.xlsm", False
  WHTTP.Send
  num = FreeFile
  On Error Resume Next
  Open ThisWorkbook.Path & "\file.xlsm" For Binary Access Write As num
  If Err.Number <> 0 Then
    Workbooks(ThisWorkbook.Path & "\file.xlsm").Close
    Open ThisWorkbook.Path & "\File.xlsm" For Binary Access Write As num
  End If
  On Error GoTo 0
  Put num, , WHTTP.ResponseBody
  Close num
  Workbooks.Open ThisWorkbook.Path & "\file.xlsm"
  If Workbooks.Count = 1 Then
    Application.Quit
  Else
    ThisWorkbook.Close
  End If
End Sub

我现在遇到的问题是来自服务器的新下载文件以某种方式被破坏(它在Excel修复文件的消息之后起作用)。

1 个答案:

答案 0 :(得分:1)

将宏分为两部分,并使用OnTime触发第二部分 first 。这是一个例子:

$complete = (int) $complete;
fad_id = (int) $fad_id;
$sender = (int) $sender;
$reciever = (int) $reciever;

$d_sql = $connect->query("
  CREATE EVENT stop_fad_1 ON SCHEDULE 
    AT CURRENT_TIMESTAMP + INTERVAL 1 MINUTE 
    ON COMPLETION PRESERVE 
  DO 
    UPDATE fad SET active_status=$complete_status 
    WHERE fad_id=$fad_id AND sender=$sender AND reciever=$reciever
  ");