通过VBA从共享工作簿中将工作表另存为PDF

时间:2014-04-15 08:45:23

标签: excel vba pdf excel-vba

我在ThisWorkbook_Open上调用了以下VBA代码,该代码将检查当天是否有该周的工作表(它是人们填写的时间表)。它会查看最近一周(星期六开始)是否已经是一张有效的工作表,如果不是,它知道本周已经结束并生成该周的报告(按PDF)并为当周创建一个新工作表。

Sub getFirstDayofWeek()
Application.ScreenUpdating = False
Dim ws As Worksheet
Dim summWS As Worksheet
Dim loopSht As Worksheet
Dim thisWeek As String, lastWeek As String
Dim dateExists As Boolean
dateExists = False
Set summWS = ThisWorkbook.Sheets("Summary")
thisWeek = Format(Now() - Weekday(Now(), vbSaturday) + 1, "ddmmyy")
lastWeek = Format(Now() - Weekday(Now(), vbSaturday) - 6, "ddmmyy")
For Each loopSht In ThisWorkbook.Worksheets
If loopSht.Name = thisWeek Then
dateExists = True
Exit For
End If
Next
If dateExists Then
Debug.Print "Do nothing"
Else
Debug.Print "Do something"

runReport ("\\save\report\here\")

Sheets("Template").Copy After:=Sheets("Summary %")
Set ws = ActiveSheet
ws.Name = thisWeek
ws.Range("A1").Value = Now() - Weekday(Now(), vbSaturday) + 1
summWS.Rows("25:26").Copy
summWS.Rows("25:25").Insert Shift:=xlDown
Application.CutCopyMode = False
summWS.Rows("5:26").Replace What:=lastWeek, Replacement:=thisWeek, LookAt:=xlPart
End If
Sheets(thisWeek).Activate
Application.ScreenUpdating = True
End Sub

和子做保存...

Sub runReport(Optional fileString As String = "C:\Temp\")
Dim reportWeek As String, filePath As String

If Right(fileString, 1) <> "\" Then
fileString = fileString & "\"
End If

reportWeek = Format(Now() - Weekday(Now(), vbSaturday) - 6, "ddmmyy")

If Dir(fileString, vbDirectory) = vbNullString Then
fileString = "\\another\backup\failsafe\path\"
MsgBox "Filepath not found. Will be saved as " & fileString
End If

filePath = fileString & "Times PDF - " & reportWeek & ".pdf"
Sheets(Array("Summary", "Summary %", reportWeek)).Select
Application.DisplayAlerts = False
ThisWorkbook.SaveAs filePath, 57
Application.DisplayAlerts = True

End Sub

我发现当共享工作簿时,我在打开时出现1004: Method 'SaveAs' or object '_Workbook' failed错误,但是如果我取消共享工作簿,那么它可以正常工作。显然,评论runReport行也可以使其正常工作。

需要共享工作簿(因为它是许多人使用的时间表),因此删除共享不是一种选择。

有什么想法吗?感谢

1 个答案:

答案 0 :(得分:0)

(忘了这个问题!)

为此找到了解决方法。不完全解决为什么它在这种情况下不起作用,但我在保存PDF时暂时取消共享VBA中的工作簿,然后立即重新启用共享。

不理想并且不确定是否有其他问题可能会导致其他人在那个确切的时间打开它,但它可以满足我的需求(因为我们只有少数几个人使用它而且我们都在每个人的呼喊距离内其他;))