2017-04-21 95 views
-4

我很难在excel 2016的Excel 2010文档中运行脚本。 一些背景: 这是一组复杂的工作表,用于记录风险和与个别化学品有关的危险。它花了很长时间的作者,但现在在2010年工作正常,但第一个脚本在Excel 2016中打破,我的猜测是它不会只是一个问题。在excel 2016中运行excel 2010 VBA脚本 - 一连串的错误

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

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 

的问题开始与“编译错误:预期数组”和LBOUND突出。 现在,我发现一些新的版本的Excel(或VBA?)需要设置Option Explicit,所以我这样做了,并且我已经声明了我的变量(或者我认为) - 但也许是这样不是实际的问题?再一次,这里可能不只是一个问题。

我迷路了。

+1

我使用的是Excel 2010,我向你保证,该版本中也存在问题。你不能做'LBound(非法)',因为你声明'非法'不是数组。较新版本的Excel不需要**'Option Explicit',但是最好使用它,就像在早期版本中使用它是一个好主意。也许你添加了(不正确的)声明,然后**开始解决你的问题了?像'Do''循环直到fname <> False'在2010年可能会导致无限循环,就像它们在更新的版本中一样。 – YowE3K

+2

*新版本的Excel(或VBA?)需要Option Explicit设置* - 哦,我多么希望它是这种情况! –

+0

@ Mat'sMug如果Option Explicit是强制性的,那么SO的excel-vba标签就会变得多余。 – YowE3K

回答

2

您需要对代码进行的更正包含在下面,但这些更改都不是由于从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 
+0

感谢YowE3K,它工作起来这看起来像一个令人讨厌的“不应该开始工作但它做了“问题。我确信我的代码中剩下的电子表格中有更多的... –