用于对未运行的文件夹中的所有excel文件执行公式的代码?

时间:2014-03-24 18:11:48

标签: excel-vba vba excel

=我有一个代码对文件夹目标中的所有Excel(.xls)文件执行一系列计算,并将特定数字放在指定的单元格中(G2,H2,I2,M2和O1)。唯一的问题是当我点击运行时代码没有响应。它没有给出错误。我在这里出错了什么想法?

Sub Code()

    Dim file As String
    Dim wbResults As Workbook
    Dim i As Long
    Dim myPath As String

    Application.ScreenUpdating = False
    Application.DisplayAlerts = False

    myPath = "C:\Location\"

    file = Dir$(myPath & "*.xls*")

    While (Len(file) > 0)
        Set wbResults = Workbooks.Open(Filename:=myPath & file, UpdateLinks:=0)

        With wbResults.Worksheets(Split(file, ".")(0))
            i = .Cells(.Rows.Count, 2).End(xlUp).Row

            With .Range("G2")
                .Formula = "=0"
            End With

            With .Range("G3:G" & i)
                .Formula = "=SQRT(((E3-E2)^2)+((F3-F2)^2))"
            End With

            With .Range("H2")
                .Formula = "=1"
            End With

            With .Range("H3:H" & i)
                .Formula = "=G3+H2"
            End With

            With .Range("I2")
                .Formula = "=1"
            End With

            With .Range("I3")
                .Formula = "=IF(D3>=SUM($I$2:I2*2.5+$O$1),1,0)"
            End With

            With .Range("I4:I" & i)
                .Formula = "=IF(D3>=SUM($I$3:I3)*2.5+$O$1,1,0)"
            End With

            With .Range("J2:K" & i)
                .Formula = "=IF($I2=1,D2,J1)"
            End With

            With .Range("K2:K" & i)
                .Formula = "=IF($I2=1,H2,K1)"
            End With

            With .Range("L2:L" & i)
                .Formula = "=IF(I2=1,(J2-J1)/(K2-K1),"")"
            End With

            With .Range("M2")
                .Formula = "=0"
            End With

            With .Range("M3:M" & i)
                .Formula = "=IF(L3="",M2,L3)"
            End With

            With .Range("O1")
                .Formula = "=177.5"
            End With

        End With

        wbResults.Close SaveChanges:=True
        file = Dir
    Wend

    Application.DisplayAlerts = True
    Application.ScreenUpdating = True
End Sub

1 个答案:

答案 0 :(得分:1)

注释掉这些行以进行调试。修好后,取消评论。

Application.ScreenUpdating = False
Application.DisplayAlerts = False

我看到了几个问题。

  • 如果找不到.xls扩展名的文件,则不会发生任何事情。
  • 你在公式""中有一个字符串,你必须加倍引用""""

    With .Range("L2:L" & i)
        .Formula = "=IF(I2=1,(J2-J1)/(K2-K1),"""")"
    End With
    
  • 您在这些等式的IF之前缺少等号

    With .Range("J2:K" & i)
        .Formula = "=IF($I2=1,D2,J1)"
    End With
    
    With .Range("K2:K" & i)
       .Formula = "=IF($I2=1,H2,K1)"
    End With