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

时间:2018-10-02 14:00:01

标签: excel vba excel-2016

我正在尝试在工作表中插入公式,但是第一次和第二次尝试都做得不太好。

因此,首先,我认为最好使用GetOpenFilename功能来确保准确性,而不是让用户自己输入工作簿的名称。我在编写时使用了this pagethis answer。运行代码时,将打开“打开”对话框,但是当我选择一个工作簿时,我会不断收到:

  

“运行时错误'424':必需对象”。

我不确定要求什么吗?起初我只有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")

但这给了我一个:

  

“运行系统错误'91':对象变量或未设置块变量”。

我不知道它要我做什么,我真的很感谢任何帮助!

1 个答案:

答案 0 :(得分:1)

要获取工作簿的名称(用.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*")返回工作簿路径的字符串。并且Workbooks()需要一个已经打开的工作簿名称。

尝试一下:

Sub TestMe()

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

  MsgBox mainwb.Name

End Sub