运行 excel 2010 VBA 脚本 excel 2016 - 一连串的错误

Running an excel 2010 VBA script in excel 2016 - a litany of errors

我在 excel 2016 的 excel 2010 文档中 运行 脚本时遇到问题。 一些背景: 它是一套复杂的工作表,用于记录与单个化学品相关的风险和危害。创作花了很长时间,但现在在 2010 年运行良好,但第一个脚本在 excel 2016 年出现故障,我猜这不仅仅是一个问题。

脚本做的第一件事是保存文件,包括文件名中的化学品名称:

    Private Sub CommandButton1_Click()
Dim chemical As String, illegal As String, fname As String
Dim X as Integer

    On Error Resume Next

    chemical = Range("Q13")       'this will be used as part of the filename

    If chemical <> "" Then

    Application.ScreenUpdating = False

    illegal = Array("<", ">", "|", "/", "*", "\", "?", "[", "]", ":")
        For X = LBound(illegal) To UBound(illegal)
            chemical = Replace(chemical, illegal(X), "-", 1)                'replaces illegal characters for file name
        Next X


    fname = Application.GetSaveAsFilename(InitialFileName:="Draft PAC " & chemical & ".xlsm")

        Do

        Loop Until fname <> False
        ActiveWorkbook.SaveAs Filename:=fname

    Application.ScreenUpdating = True

    Else: MsgBox "Please enter the name of the chemical into the orange shaded cell"

    End If

    End Sub

问题以 "Compile error: expected array" 开始,LBound 突出显示。 现在,我通过一些谷歌搜索发现 excel(或 VBA?)的较新版本需要设置 Option Explicit,所以我已经做到了,并且我已经声明了我的变量(或者如此)我想)——但也许这不是真正的问题?再一次,这里可能不止一个问题。

我迷路了。

下面包含了您需要对代码进行的更正,但是这些更改中的 none 是由于从 Excel 2010 升级到更高版本 - 它们在早期版本中都是必需的Excel 也是。

Private Sub CommandButton1_Click()
    'Declare illegal as a Variant array
    Dim chemical As String, illegal() As Variant, fname As String
    Dim X As Integer

    'Get rid of the On Error so that you know when something doesn't work
    'On Error Resume Next

    chemical = Range("Q13").Value       'this will be used as part of the filename

    If chemical <> "" Then

        Application.ScreenUpdating = False

        illegal = Array("<", ">", "|", "/", "*", "\", "?", "[", "]", ":")
        For X = LBound(illegal) To UBound(illegal)
            chemical = Replace(chemical, illegal(X), "-", 1)                'replaces illegal characters for file name
        Next X

        'Put "fname = " within the loop so that it isn't an infinite loop
        'if the user does not select a filename
        Do
            fname = Application.GetSaveAsFilename(InitialFileName:="Draft PAC " & chemical & ".xlsm")
        Loop Until fname <> False
        ActiveWorkbook.SaveAs Filename:=fname

        Application.ScreenUpdating = True

    Else
        MsgBox "Please enter the name of the chemical into the orange shaded cell"
    End If

End Sub