VBA循环文件夹公式粘贴问题

我写了一个macros,可以成功循环一个文件夹,将信息复制并粘贴到一个新的工作簿,并插入三个公式。 我有问题,但是,我调用的一些macros中的索引函数显示不正确。

Sub LoopAllExcelFilesInFolder() Application.ScreenUpdating = False Dim MyFolder As String Dim MyFile As String MyFolder = "C:\Users\myname\Desktop\Test Files" MyFile = Dir(MyFolder & "\*.xlsx") 'This is where my loop code starts Do While MyFile <> "" Workbooks.Open Filename:=MyFolder & "\" & MyFile, UpdateLinks:=0 Sheets("Report").Activate Sheets("Report").Cells.Select Application.CutCopyMode = False Application.DisplayAlerts = False Selection.Copy ActiveWorkbook.Close True Windows("Database Loop Test.xlsm").Activate Sheets("PORT").Activate Range("A1").Select ActiveSheet.Paste 'It is successfully pasted to the desired workbook 'Here I call macros that insert sum, mid, and index functions. Sum and mid work but index doesn't Call icvba Call iovba Call idvba MyFile = Dir Loop End Sub 

奇怪的是,当我运行macros后检查索引函数时,它们都是正确的。 它显示为#N / A,而不是显示正确的数字。 这是我打电话的macros的代码。 所有三个代码是相同的; 只有工作表正在改变。

 Sub icvba() Worksheets("COMMIT").Activate Dim source As Worksheet Dim detntn As Worksheet Dim EmptyColumn As Long Dim LastRow As Long Set source = Sheets("vlookup") Set detntn = Sheets("COMMIT") LastColumn = detntn.Cells(1, detntn.Columns.Count).End(xlToLeft).Column LastRow = Worksheets("COMMIT").Range("A:A").Rows.Count 'This if statement inputs the troublesome index function If detntn.Range("A2") <> "" Then EmptyColumn = LastColumn + 1 detntn.Cells(3, EmptyColumn).Formula = "=INDEX(PORT!$S$5:$S$4000,MATCH(COMMIT!$G3,PORT!$G$5:$G$4000,0))" LastRow = ActiveSheet.UsedRange.Rows.Count detntn.Cells(3, EmptyColumn).AutoFill destination:=detntn.Range(detntn.Cells(3, EmptyColumn), detntn.Cells(LastRow, EmptyColumn)) End If 'This if statement inputs the mid function If detntn.Range("A2") <> "" Then detntn.Cells(2, EmptyColumn).Formula = "=MID(PORT!$A$2,7,50)" End If 'This if statement inputs a sum function If detntn.Range("A2") <> "" Then Worksheets("vlookup").Activate ActiveSheet.Range("A1").Select Selection.Copy Worksheets("COMMIT").Activate detntn.Cells(1, EmptyColumn).Select Selection.PasteSpecial Paste:=xlAll End If Columns(EmptyColumn).Select Selection.Copy Selection.PasteSpecial Paste:=xlPasteValuesAndNumberFormats Application.CutCopyMode = False End Sub 

另外,当我单独调用icvba,iocba,idvbamacros时,它们完美地工作。 只有在我的循环函数中调用它们时,才会停止工作。

这是我用VBA编写的第一个循环,所以我可能会错过简单的东西。 我只是不知道我要去哪里错了。 任何帮助将非常感激!

听起来像公式只是没有计算 – 尝试把这之前就复制粘贴专用最后:

 Not_Calculated: Application.Wait(Now + TimeValue("0:00:04")) if not Application.CalculationState = xlDone then goto Not_Calculated 

基本上,这个macros暂停了4秒钟,让计算完成,如果还没有等待4秒