vba代码没有从文件中获取正确的单元格值

这是我的代码:

Dim RowLast As Long Dim sunmLast As Long Dim tempLast As Long Dim filterCriteria As String Dim perporig As Workbook Dim x As String tempLast = ThisWorkbook.Sheets("combine BOMs").Cells(Rows.Count, "E").End(xlUp).Row Range("D5:G" & tempLast).ClearContents Range("G5:G" & tempLast).Interior.ColorIndex = 0 tempLast = ThisWorkbook.Sheets("combine BOMs").Cells(Rows.Count, "A").End(xlUp).Row Range("A5:A" & tempLast).ClearContents tempLast = ThisWorkbook.Sheets("combine BOMs").Cells(Rows.Count, "B").End(xlUp).Row 'Perpetual Set perporig = Workbooks.Open("\\Etnfps02\vol1\DATA\Inventory\Daily tracking\perpetual.xlsx", UpdateLinks:=False, ReadOnly:=True) RowLast = perporig.Sheets("perpetual").Cells(Rows.Count, "A").End(xlUp).Row perporig.Sheets("perpetual").Cells(3, 1) = "Part Number" For i = 5 To tempLast Cells(i, 1) = i - 4 perporig.Sheets("perpetual").AutoFilterMode = False filterCriteria = ThisWorkbook.Sheets("combine BOMs").Range("B" & i).Value perporig.Sheets("perpetual").Range("A3:J" & RowLast).AutoFilter Field:=1, Criteria1:=filterCriteria Counter = perporig.Sheets("perpetual").Cells(RowLast + 1, 1).End(xlUp).Row If Counter = 3 Then Cells(i, 5).Value = "Not on perpetual" Else ThisWorkbook.Sheets("combine BOMs").Cells(i, 5).Value = WorksheetFunction.Sum(perporig.Sheets("perpetual").Range("H4:H" & RowLast).SpecialCells(xlCellTypeVisible)) x = perporig.Sheets("perpetual").Cells(Cells(RowLast + 1, 1).End(xlUp).Row, 4).Value MsgBox x, vbOKOnly, perporig.Sheets("perpetual").Cells(RowLast + 1, 1).End(xlUp).Row ThisWorkbook.Sheets("combine BOMs").Cells(i, 4).Value = x End If perporig.Sheets("perpetual").AutoFilterMode = False Next perporig.Close savechanges:=False 

这是我点击我的button(或ThisWorkbook)的文件,
在这里输入图像说明

这是在最后一行数据上运行的永久文件:
在这里输入图像说明

请注意D9280的不同之处:在永久文件中显示的库存types为“P”,而最终结果中的“B”显示在ThisWorkbook中的单元格D12中。 为了debugging,我创build了一个Msgbox提示符,每次获取所有行的值。 对于其他行,它给出正确的值(“P”),但对于这个,msgbox显示“B”。 msgbox的标题是行号,这表明它正在获取正确的行,只是我不知道为什么它是错误的值。 我曾尝试过不同的数据源,似乎每隔一段时间都会在错误的地方出现“B”。

在代码中,就在这条线的上方,我有一条线来获得现有的数量,它正确地采取了(我用xltypevisible来粘贴这个字段的值,但那只是因为我想要一个结果的总和,这是我知道的唯一方法)。 只有这个随机显示错误值的库存types列。

有任何想法吗?
谢谢!

1)

 Cells(i, 1) = i - 4 

正如它所写的,它指perporig.Cells(i, 1)是你想要的吗?

2)

 perporig.Sheets("perpetual").Range("A3:J" & RowLast).AutoFilter Field:=1, Criteria1:=filterCriteria 

会从第3行过滤,而第4行的标题和第5行的数据向下

改变它

  perporig.Sheets("perpetual").Range("A4:J" & RowLast).AutoFilter Field:=1, Criteria1:=filterCriteria 

3)

你怎么看Counter呢? 不一定只计数可见的行

find窗口的信贷,我find了答案。 .cells(cells())部分对于内部单元格()没有正确的工作表参考:

代替

  x = perporig.Sheets("perpetual").Cells(Cells(RowLast + 1, 1).End(xlUp).Row, 4).Value MsgBox x, vbOKOnly, perporig.Sheets("perpetual").Cells(RowLast + 1, 1).End(xlUp).Row 

我用这个:

  With perporig.Sheets("perpetual") x = .Cells(.Cells(RowLast + 1, 1).End(xlUp).Row, 4).Value MsgBox x, vbOKOnly, .Cells(RowLast + 1, 1).End(xlUp).Row End With 

它的工作。
谢谢你的帮助!