Home » excel » excel vba – Setting variables VBA error

excel vba – Setting variables VBA error

Posted by: admin May 14, 2020 Leave a comment

Questions:

I am getting an error when trying to execute the following subroutine

“Runtime Error: 9, Subscript out of range”

its highlighting the first variable declaration. At first I thought it was due to the wrong datatype but changing and playing around with that had no luck.

I also tried both Cells & Range

Public vFolderPath As String
Public vCMFNewPath As String
Public vKBNewPath As String
Public vDPI As Integer

Private Sub SetGlobal()

Dim vGo As String
Dim vTemplateLocation As String
Dim vCMFFilename As String
Dim vKBFilename As String
Dim vDriver As String
Dim vPKG As String

    vDPI = Workbooks("tools.xlsm").Sheets("SETTINGS").Range("B2").Value

    vFolderPath = Workbooks("tools.xlsm").Sheets("SETTINGS").Range("B3").Value & "\"

Any ideas?

How to&Answers:

Code works fine, running from a file called Tools.xslm. with a tab called Settings, an integer in cell B2 and a string value in cell B3.

This works when running from a module in Personal xlsb or from within Tools.xlsm. It works even if you do not declare any of the variables.

Answer:

Try below code :

Public vFolderPath As String
Public vCMFNewPath As String
Public vKBNewPath As String
Public vDPI As Integer

Private Sub SetGlobal()


    Dim vGo As String
    Dim vTemplateLocation As String
    Dim vCMFFilename As String
    Dim vKBFilename As String
    Dim vDriver As String
    Dim vPKG As String

    Dim wkbSetting As Workbook, shtSetting As Worksheet

    On Error Resume Next
    Set wkbSetting = Workbooks("tools.xlsm")
    On Error GoTo 0

    On Error GoTo err_rout
    If Not wkbSetting Is Nothing Then

        On Error Resume Next
        Set shtSetting = wkbSetting.Sheets("SETTINGS")
        On Error GoTo 0

        On Error GoTo err_rout
        If shtSetting Is Nothing Then
            Err.Raise Number:=32, Description:="Sheets Settings not found"
        End If


        vDPI = CInt(shtSetting.Range("B2").Value)
        vFolderPath = shtSetting.Range("B3").Value & "\"

    Else
        Err.Raise Number:=31, Description:="Workbook - tools.xlsm not found"
    End If


Exit Sub
err_rout:
    MsgBox Err.Description, vbInformation

End Sub