【发布时间】:2015-11-14 14:46:03
【问题描述】:
我有一个工作簿,其中包含来自所有分支机构的所有发票的列表,我们称之为“一切”,基本上我需要搜索是否在包含每个分支机构发票的另一个文件中找到发票。它实际上是每个分支的文件,每个文件按月用工作表划分,我需要检查每个工作表,然后在单元格中插入一个值。让我们将其称为“0001”,以此类推每个分支。
“所有”文件基本上包含一列分行编号、一列发票编号、一列发行人代码和一列是否在分行文件中找到。分支文件除了分支编号之外包含相同的内容,最后一列说明发票是否在“Everything”文件中。在某些情况下,发票在分支文件上而不在“所有文件”上,也有发票在所有文件上而不在分支文件上的情况。
我试图做的是在 VBA 中插入一个循环,以便它会在所有文件中的发票后自动开票并打开特定的分支文件,然后在每张表中搜索发票编号。我还需要检查发行者是否相同,但首先我尝试了这段代码,当它搜索该值时,它返回了错误的单元格!代码如下:
Dim sh As Worksheet
Dim iLoop As Integer
For iLoop = 7 To 1719
' this is where the invoices are in an excel sheet
iloopoffset = iLoop - 6
' as you see above, the list of invoices starts at line 7, so I used this to offset
If Range("K6").Offset(iloopoffset).Value = "No" Then
' Column K is the one saying if the invoice was found or not in the branches file
Set searchedvalue = Range("B6").Offset(iloopoffset, 0)
' I used this so i could use the value in the .find formula
MsgBox (searchedvalue.Value)
Workbooks.Open ("C:\Users\xxxxxx\Documents\xxxxxx\XML " + Range("D6").Offset(iloopoffset).Value)
For Each sh In Worksheets
If ActiveSheet.Name = "062015" Or "052015" Or "042015" Or "032015" Or "022015" Or "012015" Or "122014" Or "112014" Then
' I needed to do this because on the sheets with the names above, the searched value will be in another column. sheets before 112014 are different.
Set NFE = Worksheets(sh.Name).Range("B:B").Find(Range("B6").Offset(iloopoffset, 0).Value, lookat:=xlPart)
Else
Set NFE = Worksheets(sh.Name).Range("A:A").Find(Range("B6").Offset(iloopoffset, 0).Value, lookat:=xlPart)
End If
If Not NFE Is Nothing Then
MsgBox ("Found on sheet " + ActiveSheet.Name + " " + NFE.Address)
Range(NFE.Address).Offset(, 12).Value = "YES"
' yes for found
ActiveWorkbook.Save
ActiveWindow.Close
End If
Next sh
ActiveWorkbook.Save
ActiveWindow.Close
End If
Next iLoop
End Sub
发生了什么事?我是 VBA 中的真正菜鸟,但我没有发现这段代码有什么问题……你能帮帮我吗?
【问题讨论】:
-
试试
Set NFE = Worksheets(sh.Name).Range("B:B").Find(searchedValue.Value, lookat:=xlPart) -
感谢布鲁斯,但没有奏效。在它搜索的第一张纸上返回单元格B1210,当搜索到的值为72266时,其中的值为62385...
-
在您需要始终使用
sh,而不是Activesheet的工作表循环内 - 当sh更改时,活动工作表不会更改 -
谢谢蒂姆,但也没有用。和以前一样……
-
使用这行代码“For Each sh In Worksheets”,您是否尝试 (a) 循环您刚刚在上一行代码中打开的工作簿中的工作表,(b) 循环包含您的 VBA 代码或 (c) 其他内容的工作簿?