2017-04-21 108 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,它工作起來這看起來像一個令人討厭的「不應該開始工作但它做了「問題。我確信我的代碼中剩下的電子表格中有更多的... –