如何确保VBA代码将工作簿保存到声明的文件path中?
以下是我的代码,试图删除一些工作表,以便只保存具有特定工作表的工作簿:
Sub SeperateWB2() Dim ws As Worksheet Dim wb As Workbook Dim sheetname As Variant Dim ddl As Variant 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 & ws.Name & ".xlsx", Excel.XlFileFormat.xlOpenXMLWorkbook wb.Close Set wb = Nothing End Sub
循环工作正常,但它拒绝将工作簿保存在我指定的path。
我收到以下消息:“运行时错误91:对象variables或块variables未设置”
谁能帮忙?
wb
对象variables永远不会被分配给Nothing
以外的Nothing
。 但无论如何,您可以使用ThisWorkook
,如果您的意思是保存并closures包含运行代码的工作簿:
With ThisWorkbook .SaveAs Path & ws.Name & ".xlsx", Excel.XlFileFormat.xlOpenXMLWorkbook .Close End With
看看你的错误消息: 对象variables或块variables未设置
看起来你无法保存,因为你永远不会实例化你的wb
variables。 所以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
感谢大家!
看来我需要正确Set wb = ThisWorkbook
工作簿( 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