2012-09-14 24 views
0

我有一個特定的文件名下面的代碼:在通過各種文件循環時在VBA中編寫公式?

BD.Sheets("Sheet1").Cells(Rows.Count, 6).End(xlUp).Offset(1, 0).Formula = "=SUMIF('P:\Actuary\Cash Flow Forecast\Annual and Quarterly Budget Data\[ECMQA 2012Q1.xls]Sheet1'!$D$13:$D$234,D2,OFFSET('P:\Actuary\Cash Flow Forecast\Annual and Quarterly Budget Data\[ECMQA 2012Q1.xls]Sheet1'!$D$13:$D$234,0,MATCH(E2,'P:\Actuary\Cash Flow Forecast\Annual and Quarterly Budget Data\[ECMQA 2012Q1.xls]Sheet1'!$D$12:$R$12,0)-1))" 

不過,我運行一個循環進入一個文件夾,在其中選擇所有文件(以上文件是該文件夾中,我在測試我的代碼了,看看它是否工作了一個文件):

Dim wb As Workbook, sFile As String, sPath As String 
Dim itm As Variant 
Dim strFileNames As String 

sPath = "C:\Actuary\Cash Flow Forecast\Annual and Quarterly Budget Data\" 

''Retrieve the current files in directory 
sFile = Dir(sPath) 
Do While sFile <> "" 
    strFileNames = strFileNames & "," & sFile 
    sFile = Dir() 
Loop 

''Open each file found 
For Each itm In Split(strFileNames, ",") 
    If itm <> "" Then 
     Set wb = Workbooks.Open(sPath & itm) 

     ''LOTS OF CALCULATIONS, INCLUDING ABOVE CODE 


    End If 
Next itm 

我怎麼會寫的第一個代碼,如果我不知道文件名(因爲它是通過循環所有的)?

任何幫助將不勝感激!

回答

0
Sub WriteFormulas() 

    Dim sFile As String 
    Dim sPath As String 
    Dim sh As Worksheet 
    Dim rNext As Range 

    sPath = Environ("USERPROFILE") & "\My Documents\Tester\" 

    'Get the first file 
    sFile = Dir(sPath & "*.xls") 

    Do While Len(sFile) > 0 
     'don't process this workbook 
     If sFile <> ThisWorkbook.Name Then 
      'set a variable to the first sheet in the file 
      Set sh = Workbooks.Open(sFile).Worksheets(1) 
      'find the next available cell in column A in this workbook 
      Set rNext = Sheet1.Cells(Sheet1.Rows.Count, 1).End(xlUp).Offset(1, 0) 
      'create a formula using the address with the external argument 
      rNext.Formula = "=SUM(" & sh.Range("A1:A10").Address(True, True, xlA1, True) & ")" 
      'close the workbook 
      sh.Parent.Close False 
     End If 
     sFile = Dir 
    Loop 

End Sub 

當您關閉工作簿時,Excel將展開對完整路徑和文件名的引用。因此,儘管Range("A1").Address(,,,true)可能會解決到

[MyBook.xls]Sheet1!A1 

當您關閉MyBook.xls,它會轉換成

'C:\Path\[MyBook.xls]Sheet1'!A1 
+0

首先,非常感謝你的幫助!然而,如果我只想在打開時顯示'[MyBook.xls]'或者在C:\ Path \ [MyBook中顯示'[MyBook.xls]',代碼中的Range(「A1:A10」)' .xls]'何時關閉?我正在修復工作表和單元格,因爲它們對於每個文件總是相同的。 – Kristina

+0

這個問題也不是我所有的文件都有.xls擴展名,它們是.xls或.xlsx,所以我使用其他代碼... – Kristina

+0

這就是它現在所做的 - 擴展打開時的路徑,合同關閉時。使用範圍對象的Address屬性允許Excel構建字符串。但是,如果你願意,你可以建立字符串。像'.Formula =「= SUMIF(''&sPATH&」[「&sFile&」]「&」Sheet1'!$ D $ 13:$ D $ 234,D2,OFFSET('「&sPath&」[「&sFile &「] Sheet1'!$ D $ 13:$ D $ 234,0,MATCH(E2,'」&sPATH&「[」&sFile&「] Sheet1'!$ D $ 12:$ R $ 12,0)-1)) 「」即使你這樣做,我也會得到Excel合同並擴展它。 –