为什么我在尝试获取工作簿名称的用户输入时收到对象必需错误

Why am I getting an object required error when trying to get user input for the name of a workbook

我正在尝试将公式插入到我的工作表中,但我的第一次和第二次尝试都不太顺利。

所以,首先我认为为了准确起见,最好使用 GetOpenFilename 功能,而不是让用户自己输入工作簿的名称。我在写的时候用了this page and this answer。当我 运行 代码时,“打开”对话框打开,但是当我 select 工作簿时,我不断收到:

"Runtime Error '424': object required".

我不确定它要求什么?起初我只有 Application.GetOpenFilename(),所以我认为我需要添加过滤器,但它没有帮助。

    Sub openfile()

Dim mainwb As Workbook
Set mainwb = Application.GetOpenFilename("Microsoft Excel Files, *.xls*")

Dim mainws As Worksheet
mainws = InputBox("Please enter the name of the worksheet")

Dim rdsMonthly As Variant
rdsMonthly = InputBox("Please insert current month column in format $A:$A")

Dim rdsID As Variant
rdsID = InputBox("Please insert ID column in format $A:$A")

Cells(8, 14) = "=IFERROR(SUMIFS('[" & mainwb & "]" & mainws & "'!" & rdsMonthly & ", '[" & mainwb & "]" & mainws & "'!" & rdsID & ", $C55), " & Chr(34) & Chr(34) & ")"


End Sub

之后,我尝试使用输入框代替

 Dim mainwb As Workbook
mainwb = InputBox("Please enter the name of the workbook, including file extension")

但这给了我一个:

"Runtime error '91': Object variable or With block variable not set".

我不知道它想要我做什么,非常感谢任何帮助!

要获取工作簿的名称,用.GetOpenFileName表示,可以将大字符串拆分一次/,然后获取最后一项。然后,再次按 .xls 拆分并取第 0 项。 1 行这 2 个操作如下所示:

Sub TestMe()

    Dim filePath As String
    filePath = Application.GetOpenFilename("Microsoft Excel Files, *.xls*")

    Dim nameOfWb As String
    'do not do this at production, but split it to variables:
    nameOfWb = Split(Split(filePath, "\")(UBound(Split(filePath, "\"))), ".xls")(0)
    Debug.Print nameOfWb

End Sub

Application.GetOpenFilename("Microsoft Excel Files, *.xls*") returns 工作簿路径的字符串。 Workbooks() 需要一个已经打开的工作簿名称。

试试这个:

Sub TestMe()

  Dim mainwb As Workbook
  Set mainwb = Workbooks.Open(Application.GetOpenFilename("Microsoft Excel Files, *.xls*"))

  MsgBox mainwb.Name

End Sub