以下是我的代码,试图删除大量工作表,以便仅保存具有特定工作表的工作簿:
https://www.google.com/thats/a/test
循环工作正常,但它拒绝将工作簿保存在我指定的路径上。
我收到此消息:“运行时错误91:对象变量或未设置块变量”
有人可以帮忙吗?
答案 0 :(得分:2)
查看您的错误消息:对象变量或使用块变量未设置
看起来您无法保存,因为您从未实例化wb
变量。因此wb = Nothing
。您无法在任何情况下执行SaveAs
。尝试在声明下添加Set wb = ThisWorkbook
,如下所示:
'other code
Dim ws As Worksheet
Dim wb As Workbook
Dim sheetname As Variant
Dim ddl As Variant
Set wb = ThisWorkbook
ddl = "PhaseTransferDropDowns"
'other code
答案 1 :(得分:1)
永远不会将Nothing
对象变量分配给ThisWorkook
以外的任何内容。但无论如何,如果您要保存并关闭包含正在运行的代码的工作簿,则可以使用With ThisWorkbook
.SaveAs Path & ws.Name & ".xlsx", Excel.XlFileFormat.xlOpenXMLWorkbook
.Close
End With
:
{{1}}
答案 2 :(得分:0)
谢谢大家!
我似乎需要正确设置工作簿(Set wb = ThisWorkbook
)。
我还需要将ws.name
更改为sheetname
。
这是最后工作的代码:
Sub SeperateWB2()
Dim ws As Worksheet
Dim wb As Workbook
Dim sheetname As Variant
Dim ddl As Variant
Set wb = ThisWorkbook
ddl = "PhaseTransferDropDowns"
sheetname = InputBox("Please specify sheet name:")
Path = "C:\My Documents\Phase Transfer\Test\"
For Each ws In ThisWorkbook.Worksheets 'SetVersions
If Not ws.Name = sheetname And Not ws.Name = ddl Then
Application.DisplayAlerts = False
ws.Delete
End If
Next ws
wb.SaveAs Path & sheetname & ".xlsx", Excel.XlFileFormat.xlOpenXMLWorkbook
'wb.Close
End Sub