[英]Error when saving a new file using SaveAs function in vba
我正在接受輸入框中的日期並過濾我的數據並將其保存在新工作簿中。 當我保存這個新工作簿時,它給了我一個運行時錯誤 1004,其中包含以下語句:
方法 'SaveAs'of object'_Workbook' 失敗。
我無法找到解決方案。
Sub GIACTSDS121()
Dim dte As Date
mBox = InputBox("Enter a date")
If IsDate(mBox) Then
dte = CDate(mBox)
Dim Lastrow As Long
Lastrow = ActiveSheet.Range("A" & Rows.Count).End(xlUp).Row
ActiveSheet.Range("A1:AC" & Lastrow).AutoFilter Field:=2, Criteria1:=">=" & dte, _
Operator:=xlAnd, Criteria2:="<" & dte + 1
Range("U1").Select
ActiveSheet.Range("A1:AC" & Lastrow).AutoFilter Field:=21, Criteria1:="Yes"
Range("A1").Select
Range(Selection, Selection.End(xlDown)).Select
Range(Selection, Selection.End(xlToRight)).Select
Selection.Copy
Workbooks.Add
ActiveSheet.Paste
ActiveSheet.Range("A:A,E:E,I:I,M:N,Q:T,X:Z").EntireColumn.Delete
ActiveWorkbook.SaveAs Filename:="K:\K_Drive\RP\RPS-Metrics-ops\' Operations Metrics\Investigation Documentation\GIACT Investigations\SDS_Cases\_" & dte & ".xlsx", FileFormat:=51
ActiveWorkbook.Close
Else
MsgBox "This is not a date. Please try again"
End If
End Sub
傳遞給SaveAs
的Filename
參數包含 windows 不接受文件名的無效字符
Filename:="K:\K_Drive\RP\RPS-Metrics-ops\' Operations
^
|
maybe this is the cause!
Get rid of all ActiveSheet
, ActiveWorkbook
and all .Select
if possible (see How to avoid using Select in Excel VBA ).
還要為位於Range
、 Cells
、 Rows
、 Columns
等工作表中的每個object 指定一個工作表。
Public Sub GIACTSDS121()
Dim ws As Worksheet
Set ws = ActiveSheet 'better define by name as: Set ws = ThisWorkbook.Worksheets("Sheet1")
Dim mBox As Variant
mBox = InputBox("Enter a date")
If IsDate(mBox) Then
Dim dte As Date
dte = CDate(mBox)
Dim LastRow As Long
LastRow = ActiveSheet.Range("A" & ws.Rows.Count).End(xlUp).Row
ws.Range("A1:AC" & LastRow).AutoFilter Field:=2, Criteria1:=">=" & dte, _
Operator:=xlAnd, Criteria2:="<" & dte + 1
ws.Range("A1:AC" & LastRow).AutoFilter Field:=21, Criteria1:="Yes"
ws.Range(ws.Range("A1"), ws.Range("A1").End(xlDown).End(xlToRight)).Copy
Dim NewWb As Workbook
Set NewWb = Workbooks.Add
NewWb.Worksheets(1).Paste
NewWb.Worksheets(1).Range("A:A,E:E,I:I,M:N,Q:T,X:Z").EntireColumn.Delete
NewWb.SaveAs Filename:="K:\K_Drive\RP\RPS-Metrics-ops\' Operations Metrics\Investigation Documentation\GIACT Investigations\SDS_Cases\_" & dte & ".xlsx", FileFormat:=51
NewWb.Close SaveChanges:=False
Else
MsgBox "This is not a date. Please try again"
End If
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.