设置变量VBA错误

时间:2013-03-22 11:57:19

标签: vba excel-vba powerpoint-vba vbe excel

我在尝试执行以下子程序时遇到错误

“运行时错误:9,下标超出范围”

突出显示第一个变量声明。起初我认为这是由于错误的数据类型,但改变和玩弄没有运气。

我也试过Cell&范围

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 & "\"

有什么想法吗?

2 个答案:

答案 0 :(得分:3)

代码工作正常,从名为Tools.xslm的文件运行。使用名为Settings的选项卡,单元格B2中的整数和单元格B3中的字符串值。

从Personal xlsb中的模块或Tools.xlsm中的模块运行时,此方法有效。即使您没有声明任何变量,它也能正常工作。

答案 1 :(得分:0)

尝试以下代码:

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