我有一个“母版表”,其中将输入数据的多个工作簿(Station工作簿)合并到一个Master文件中。当我按下Master Sheet中的命令按钮时,我想清除Station工作簿中的数据,清除所有数据并保存为今天的日期。它还需要删除工作簿中的特定范围...
我尝试过并且仅当清除“主表”中的数据时它才起作用,但是我尝试涉及其他表的代码似乎卡住了。我使用数组从多个工作簿中擦除。我只在Station 1文件中尝试过。
Sub ClearAll()
'ClearAll & Save Macro
Dim answer As Integer
answer = MsgBox("All entries will be cleared. Are you sure?", vbYesNo + vbQuestion, "Empty Sheet")
If answer = vbYes Then
'clears station data
Dim ex As Excel.Application
Dim wrkbk As Workbook
Dim sht As Worksheet
Dim books As Variant
Dim folder As String
Dim i As Integer
folder = "C:\Users\arocmag\Documents\MasterLog"
books = Array("Station 1 Daily Log.xlsm")
Application.ScreenUpdating = False
Application.DisplayAlerts = False
On Error GoTo errH:
Set ex = New Excel.Application
For i = 0 To UBound(books)
Set wrkbk = ex.Workbooks.Open(folder & books(i))
Set sht = wrkbk.Sheets(1)
sht.Range("A2:H2").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.ClearContents
wrkbk.Close True
Next
ex.Quit
Application.ScreenUpdating = True
Application.DisplayAlerts = True
Exit Sub
errH:
ex.Quit
Application.ScreenUpdating = True
Application.DisplayAlerts = True
MsgBox Err.Description
'clears Master Sheet
Range("A2:H2").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.ClearContents
Range("I1").Select
ActiveWorkbook.Worksheets("Master Log").AutoFilter.Sort.SortFields.Clear
Selection.AutoFilter
ActiveWorkbook.SaveCopyAs ("C:\Users\arocmarg\Documents\Rotation 3 - Warehouse Leader\01 - Capstone\6_20_2019\MasterLog" & " " & Format(Now(), "mmddyyyy") & ".xlsm")
Else
'do nothing
End If
End Sub
我希望清除工作站文件并保存(不另存为)+主文件要清除并保存为AS。
答案 0 :(得分:0)
您缺少反斜杠: 更改:
folder = "C:\Users\arocmag\Documents\MasterLog"
到
folder = "C:\Users\arocmag\Documents\MasterLog\"
此外,通过ScreenUpdating和DisplayAlerts可以很好地处理错误。人们常常无法正确处理这些问题。
您也不需要执行“选择”。
sht.Range("A2:H2").Select
Range(Selection, Selection.End(xlDown)).Select
Selection.ClearContents
可以简化为:
Range(sht.Range("A2:H2"), sht.Range("A2:H2").End(xlDown)).ClearContents
继续阅读在VBA中避免“选择”的知识,您将得到更简单的代码,执行速度更快。