我有以下具有特定文件名的代码:
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 :(得分: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