如何创build条件来创buildExcel表

我想创build一个VBE代码来创build一个新的Excel工作表。

要创build一个新的工作表,我使用下面的代码,工作得很好:

Dim ws As Worksheet With ThisWorkbook Set ws = .Sheets.Add(After:=.Sheets(.Sheets.count)) ws.Name = "Savings" End With 

但是现在我需要把这个代码改成一个IF条件,这个条件可以在这个逻辑上工作:如果有一个名为“Savings”的工作表,删除它并创build一个新的工作表名为“Savings”,否则就创build工作表“Savings”。

创build工作表“储蓄”后,我想保存为一个新的文件,我想build议一个名称(如储蓄)在另存为对话框的名称字段。

谢谢你们总是帮助我

像这样的东西应该为你工作:

 Sub tgr() Dim wsSav As Worksheet Dim sSavePath As String Dim sExt As String Dim lFileFormat As Long With ThisWorkbook On Error Resume Next 'Prevent error if worksheet doesn't exist Set wsSav = .Sheets("Savings") On Error GoTo 0 'Remove error condition If Not wsSav Is Nothing Then Application.DisplayAlerts = False 'Suppress "Are you sure?" worksheet delete prompt wsSav.Delete Application.DisplayAlerts = True End If Set wsSav = .Sheets.Add(After:=.Sheets(.Sheets.Count)) wsSav.Name = "Savings" sSavePath = Application.GetSaveAsFilename("Savings") If sSavePath = "False" Then Exit Sub 'user pressed cancel sExt = Mid(sSavePath, InStrRev(sSavePath, ".") + 1) If Len(sExt) = 0 Then sExt = "xlsm" sSavePath = sSavePath & sExt End If Select Case LCase(sExt) Case "xlsm": lFileFormat = 52 Case "xlsx": lFileFormat = 51 Case "xls": lFileFormat = 56 Case Else: MsgBox "Invalid Excel file extension """ & sExt & """" & Chr(10) & _ "Unable to save file." Exit Sub End Select Application.DisplayAlerts = False 'Suppress overwrite prompt (if any) .SaveAs sSavePath, lFileFormat Application.DisplayAlerts = True End With End Sub 

这会将工作表设置为您的variables并testing它是否存在。 如果是这样,它会删除它之前使用您的代码来创build新的工作表。 这种方式的好处是你不需要一个循环来实现它

 Dim ws as worksheet On Error Resume Next Set ws = ThisWorkbook.Sheets("Savings") On Error GoTo 0 If not ws is nothing then With Application ' Disable Alerts .DisplayAlerts = False ' Delete sheet ws.delete ' Re-enable Alerts .DisplayAlerts = True End With End If With ThisWorkbook Set ws = .Sheets.Add(After:=.Sheets(.Sheets.count)) ws.Name = "Savings" End With 

这应该做的伎俩:

 Dim ws As Worksheet With ThisWorkbook For Each ws In .Worksheets If ws.Name = "Savings" Then 'If Savings exists Application.DisplayAlerts = False 'Disable warnings ws.Delete 'Delete Worksheet Application.DisplayAlerts = True 'Enable warnings Exit For End If Next ws 'Add Savings Worksheet Set ws = .Worksheets.Add(After:=.Worksheets(.Worksheets.Count)) ws.Name = "Savings" End With With Application.FileDialog(msoFileDialogSaveAs) 'SaveAs Dialog .InitialFileName = "Savings" 'Suggested Name .AllowMultiSelect = False .Show If .SelectedItems.Count > 0 Then ThisWorkbook.SaveAs .SelectedItems(1) 'Save File End If End With