我在PPT中有一个小程序,可以在Excel中复制工作表。它在Excel文件打开时有效;但是,如果我关闭Excel文件并在PPT中运行该程序,则表示运行时错误(工作表类的复制方法失败)
var combined = dtDataForExistingProducts.AsEnumerable()
.Join(dtCatalogFromMySql.AsEnumerable(),
ep => ep.Field<string>("Prod_No")
ce => ce.Field<string>("barcode"),
(ep, ce) => new {ExistingProduct = ep, CatalogEntry = ce})
.Where(m => !m.ExistingProduct.Field("Descript")
.Equals(m.CatalogEntry.Field("productname")))
.Where(m => decimal.Parse(m.ExistingProduct.Field("Retail_PRC").ToString())
!= decimal.Parse(m.CatalogEntry.Field("pricesell").ToString()))
.ToList()
;
我在PPT中运行它时没有问题,当Excel文件&#34;测试&#34;开了;如果我关闭Test excel,这段代码会给我这个错误。
任何帮助将不胜感激!
答案 0 :(得分:1)
您可以使用On Error Resume Next
和On Error Goto 0
来测试它是否像这样打开:
Public Sub test()
Dim OWB As Excel.Workbook
On Error Resume Next
Set OWB = GetObject(ActivePresentation.Path & "\Test.xlsx")
On Error GoTo 0
If OWB Is Nothing Then
MsgBox "File is not open", vbCritical
Else
OWB.WorkSheets(1).Copy after:=OWB.Sheets(1)
End If
End Sub
或者像这样,如果你想让它为你打开:
Public Sub test()
Dim OWB As Excel.Workbook
Dim sFile As String
sFile = ActivePresentation.Path & "\Test.xlsx"
On Error Resume Next
Set OWB = GetObject(sFile)
On Error GoTo 0
If OWB Is Nothing Then
On Error Resume Next
Set OWB = Excel.Application.Workbooks.Open(sFile)
On Error GoTo 0
End If
If OWB Is Nothing Then
MsgBox "Could not locate file to open", vbCritical
Else
OWB.WorkSheets(1).Copy after:=OWB.Sheets(1)
End If
End Sub