VBA错误91 - 无法设置我的范围

时间:2016-07-20 08:03:56

标签: excel vba excel-vba macros

我已经完成了非常粗略的代码,但我正在优化它。

我已经定义了我的工作表,但现在我需要定义我的2个范围,rngTo和rngFrom。 rngTo设置没有问题,但rngFrom抛出错误91,我无法理解为什么。它应该是另一个不同的?下面是我认为相关的代码部分,但可能有一些Dim未在此快照中使用:

Sub Worksheet_UpdateAllItemCostData()

Dim material As Variant
Dim fndEntry, rngTo, rngFrom As Range
Dim wb1 As Workbook, wb2 As Workbook
Dim wsTo, wsFrom As Worksheet
Dim lr As Long, I As Long, J As Long
Const sPOS As String = "Pos. "

Application.Calculation = xlCalculationManual ' Disable
Application.ScreenUpdating = False
Application.DisplayAlerts = False

Set wb1 = ThisWorkbook
Set wsTo = wb1.Sheets("Sagsnr.")

wsTo.Rows("1:1").Hidden = False

lr = wb1.Sheets("Sagsnr.").Cells(Rows.Count, "C").End(xlUp).Row

If lr < 21 Then
    Exit Sub
End If

Set wb2 = Workbooks.Open(Filename:="G:\Backoffice\Tilbudsteam\Kostdatabase\Matcost.xls", ReadOnly:=True)

Set wsFrom = wb2.Sheets("Matcost")

    For I = 21 To lr

        material = wsTo.Range("C" & I).Value

        Set fndEntry = wsFrom.UsedRange.Columns(4).Find(What:=material)

    Set rngTo = wsTo.Range("A" & I)
    Set rngFrom = wsFrom.Range("A" & fndEntry.Row)

    If Not fndEntry Is Nothing Then

            rngTo(, "B") = rngFrom(, "H")

        End If

Next I

wb2.Close
wsTo.Rows("1:1").Hidden = True

Application.Calculation = xlCalculationAutomatic 'Enable
Application.DisplayAlerts = True
Application.ScreenUpdating = True

End Sub

1 个答案:

答案 0 :(得分:1)

变化:

    Set rngTo = wsTo.Range("A" & I)
    Set rngFrom = wsFrom.Range("A" & fndEntry.Row)

    If Not fndEntry Is Nothing Then

        rngTo(, "B") = rngFrom(, "H")

    End If

要:

    If Not fndEntry Is Nothing Then

        Set rngTo = wsTo.Range("A" & I)
        Set rngFrom = wsFrom.Range("A" & fndEntry.Row)
        rngTo.Offset(0, 1) = rngFrom.Offset(0, 7)

    End If