我想创建一个新的工作簿,在其中添加一个列表,然后保存这本书。如果它存在,我需要删除以前的变体,然后保存当前。这是我的代码:
Private Sub GenerateReport_Click()
Dim wb As Workbook
Dim FilePath As String
FilePath = ThisWorkbook.Path + "\CommonReport.xls"
Set wb = Workbooks.Add
ActiveCell.FormulaR1C1 = "a1"
wb.ActiveSheet.Range("B1").Select
ActiveCell.FormulaR1C1 = "b1b"
wb.ActiveSheet.Range("C1").Select
ActiveCell.FormulaR1C1 = "3"
wb.ActiveSheet.Range("D1").Select
ActiveCell.FormulaR1C1 = "4"
wb.ActiveSheet.Range("E1").Select
ActiveCell.FormulaR1C1 = "5"
wb.ActiveSheet.Range("F1").Select
ActiveCell.FormulaR1C1 = "6"
wb.ActiveSheet.Range("G1").Select
ActiveCell.FormulaR1C1 = "7"
wb.ActiveSheet.Range("A1:G1").Select
wb.ActiveSheet.ListObjects.Add(xlSrcRange, wb.ActiveSheet.Range("$A$1:$G$1"), , xlYes).Name = "Ñïèñîê1"
wb.ActiveSheet.Range("A1:G2").Select
Application.DisplayAlerts = False
If Dir(FilePath) = vbNullString Then
wb.SaveAs Filename:=FilePath
Else
SetAttr FilePath, vbNormal
Kill FilePath
End If
End Sub
是否可以在书籍打开时删除它。如果要删除已打开的图书,如何处理错误?
答案 0 :(得分:3)
我认为没有必要删除工作簿,只是覆盖它。如果打开,请先将其关闭。例如:
Option Explicit
Private Const NEW_BOOK_NAME As String = "CommonReport"
Public Sub Test()
Dim newWorkbook As Workbook
Set newWorkbook = Workbooks.Add
With newWorkbook.ActiveSheet
[a1] = "a1"
[b1] = "b1"
[c1] = "c1"
End With
Dim filePath As String
filePath = ThisWorkbook.Path & "\" & NEW_BOOK_NAME
On Error Resume Next
Workbooks(NEW_BOOK_NAME).Close
On Error GoTo 0
Application.DisplayAlerts = False
newWorkbook.SaveAs filePath
End Sub
答案 1 :(得分:0)
您无法删除打开的工作簿。
使用以下内容检查是否打开了具有相同名称的文件:http://www.exceltip.com/st/Determine_if_a_workbook_is_already_open_using_VBA_in_Microsoft_Excel/472.html
如果此类文件已打开,请通过将FilePath
与打开的工作簿(例如Workbooks("CommonReport.xls").FullName
)进行比较来检查其是否与要删除的文件具有相同的路径,如果是,请关闭它通过使用close命令:
Workbooks("CommonReport.xls").Close SaveChanges:=False
答案 2 :(得分:0)
OlleSjögren想法应该工作。
但是,简单地使用worksheet.usedrange.clear方法清空现有工作表可能更容易。然后你可以插入你的新数据。 这应该比删除方法快得多。