Excel文件在被VBA打开时不会被填充

我正在编写一个代码来打开一个文件,并用源文件填充文件单元格。

我遇到了一个问题,我的第二个没有填充单元格。

但是,当文件已经打开,它完美的工作。

我添加了一部分代码,让excel在填充第二个文件之前等待几秒钟,但是它也不能工作。

你有想法吗?


Sub RemplirTableaux() Dim FilePath$, TargetFilePath$ Const SheetName$ = "Sheet1" FilePath = "file.xlsx" TargetFilePath$ = "C:\file.xlsx" If Not IsWorkBookOpen(TargetFilePath) Then Workbooks.Open (TargetFilePath) End If Application.Wait DateAdd("s", 5, Now()) For i = 7 To 23 If Workbooks(FilePath).Sheets("ACs").Cells(i, "A") = Cells(1, "B") Then Workbooks(FilePath).Sheets("ACs").Cells(i, "B").Value = Cells(27, "J") Workbooks(FilePath).Sheets("ACs").Cells(i, "C").Value = Cells(27, "K") 'Another filling statements End If Next End Sub Function IsWorkBookOpen(FileName As String) Dim ff As Long, ErrNo As Long On Error Resume Next ff = FreeFile() Open FileName For Input Lock Read As #ff Close ff ErrNo = Err On Error GoTo 0 Select Case ErrNo Case 0: IsWorkBookOpen = False Case 70: IsWorkBookOpen = True Case Else: Error ErrNo End Select End Function 

您需要正确限定您的Cells号码,例如:

 Sub RemplirTableaux() Dim FilePath$, TargetFilePath$ Dim wb As Workbook Dim wsSource As Worksheet Const SheetName$ = "Sheet1" FilePath = "file.xlsx" TargetFilePath$ = "C:\file.xlsx" ' change as necessary Set wsSource = Workbooks("Tableau.xlsx").Sheets("Some sheet") If Not IsWorkBookOpen(TargetFilePath) Then Set wb = Workbooks.Open(TargetFilePath) End If For i = 7 To 23 With wb.Sheets("ACs") If .Cells(i, "A").Value2 = wsSource.Cells(1, "B").Value2 Then .Cells(i, "B").Value = wsSource.Cells(27, "J").Value .Cells(i, "C").Value = wsSource.Cells(27, "K").Value 'Another filling statements End If End With Next End Sub