在我的代码中,我想提示用户输入自定义工作簿名称,然后将所述工作簿保存在桌面上。出于某种原因,当我尝试将工作簿设置为 FilePath 时,出现运行时错误 9 - 下标超出范围。我在其他帖子上做了一些调查,但我不确定为什么我仍然收到错误消息。有没有比我更好的方法/我的错误在哪里?
Dim WB As Workbook
Dim WS As Worksheet
Dim WorkbookName As String
Dim FilePath As String
WorkbookName = InputBox("What Do you Want to Name the New Workbook?")
FilePath = "C:\Users\JoeK\Desktop\" & WorkbookName & ".xlsx"
'error is at the line below
Set WB = Workbooks(FilePath)
Set WS = Sheets("Sheet1")
答案 0 :(得分:1)
Sub CreateEmptyWorkbook()
Dim wb As Workbook
Dim ws As Worksheet
Dim workbookName As String
Dim filePath As String
workbookName = "test"
filePath = GetDesktopPath & workbookName & ".xlsx"
Set wb = Workbooks.Add
wb.SaveAs filePath
wb.Close False
End Sub
Public Function GetDesktopPath() As String
GetDesktopPath = CreateObject("WScript.Shell").specialfolders("Desktop") & "\"
End Function
Set wb = Workbooks.Add
- 添加工作簿,因此它是空的;wb.SaveAs filePath
- 将其保存到桌面上的 filePath
;wb.Close False
- 也需要关闭它,False
参数用于保存更改。只要工作簿中没有做任何事情,这个arg也可以是True
;