错误91变量未定义

时间:2016-07-12 15:15:17

标签: excel vba

这是我开始使用VBA的第二天。

我有这个循环,我首先尝试匹配A列表1中的值,如果这是真的,它将继续匹配B列表2中的内容:

For i = 1 To wsforecast.Cells(wsforecast.Rows.Count, "A").End(xlUp).Row
    For j = 1 To wsregion26.Cells(wsregion26.Rows.Count, "B").End(xlUp).Row
    If Cells(i, "A").value = "AT" Then
        If Cells(i, "C").value = wsregion26.Cells(j, "B").value Then
        'rownr = j
        Let srange1 = "I" & j & ":" & "n" & j
        Range(srange1).Select
        Selection.Copy
        Windows("SP_FORECAST_macro.xlsm").Activate
        Let srange2 = "D" & i & ":" & "i" & i
        Range(srange2).Select
        Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, Transpose:=False
        End If
    End If
'Exit For
   Next j
    Next I

但是我总是得到这个错误:“91”对象变量或者没有定义块变量,而我很确定我已经定义了所有内容:

Dim wbforecast As Workbook, wbregion As Workbook
Dim wsforecast As Worksheet, wsregion10 As Worksheet, wsregion11 As Worksheet, wsregion26 As Worksheet

Set wbforecast = Workbooks("SP_FORECAST_macro.xlsm")
Set wsforecast = Workbooks("SP_FORECAST_macro.xlsm").Sheets("SP_FORECAST")
Set wbregion = Workbooks("Region.xlsm")
Set wsregion10 = Workbooks("Region.xlsm").Sheets("BE")
Set wsregion11 = Workbooks("Region.xlsm").Sheets("LU")
Set wsregion26 = Workbooks("Region.xlsm").Sheets("AT")
Dim i As Integer, j As Integer, srange1, srange2 As Range

如果你能帮助我了解导致这个问题的原因?非常感谢你们!

2 个答案:

答案 0 :(得分:1)

Let srange2 = "D" & i & ":" & "i" & i

应该是

Set srange2 = Range("D" & i & ":" & "i" & i)

Set srange2 = Range(Cells(i, "D"), Cells(i, "I"))  

Set srange2 = Range(Cells(i, 4), Cells(i, 9))

注意 - 在您的代码中,您使用Cells来标识单个单元格。您还可以使用它来识别范围内的开始和结束单元格。

答案 1 :(得分:1)

使用模块顶部的option explicit查找尚未定义的变量。

Let srange1 = "I" & j & ":" & "n" & j
        Range(srange1).Select
        Selection.Copy
        Windows("SP_FORECAST_macro.xlsm").Activate
        Let srange2 = "D" & i & ":" & "i" & i
        Range(srange2).Select
        Selection.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, Transpose:=False

可以简化为

    srange1 = "I" & j & ":" & "n" & j
    srange2 = "D" & i & ":" & "i" & i
    wsforecast.Range(srange2).Value2 = wsregion26.Range(srange1).Value2

dim srange1 as string
dim srange2 as string