我可以通過廣泛查找的GetValues函數從已關閉的工作簿抓取值;它的效果很好。從已關閉的Excel文件中抓取公式(不只是值)
但有時我需要從封閉的工作簿中獲取單元格的公式。我嘗試修改GetValues來獲取單元格公式,但我得到錯誤。
如何從封閉的excel文件中獲取單元格的公式(不是簡單的值)?
With Sheets
For r = 2 To NewRowQty ' from second row to last row
For c = 1 To ThisColumnEnd ' out to EndColumn (from import dialogue box)
ThisCell = Cells(r, c).Address
ThisValue = GetValue(ThisPath, ThisFile, ThisSheet, ThisCell)
If ThisValue <> "0" Then
If c = 3 And r > 2 Then
Cells(r, c).Formula = GetFormula(ThisPath, ThisFile, ThisSheet, ThisCell)
Else
Cells(r, c) = ThisValue
End If
End If
Next c
Next r
End With
調用這兩個函數,的GetValue工作正常,GetFormula不會搶公式。
Private Function GetValue(p, f, s, c)
'p: path: The drive and path to the closed file (e.g., "d:\files")
'f: file: The workbook name (e.g., "budget.xls")
's: sheet: The worksheet name (e.g., "Sheet1")
'c: cell: The cell reference (e.g., "C4")
'Retrieves a value from a closed workbook
Dim arg As String
'Make sure the file exists
If Right(p, 1) <> "\" Then p = p & "\"
If Dir(p & f) = "" Then
GetValue = "File Not Found"
Exit Function
End If
'Create the argument
arg = "'" & p & "[" & f & "]" & s & "'!" & _
Range(c).Range("A1").Address(, , xlR1C1)
'Execute an XLM macro
GetValue = ExecuteExcel4Macro(arg)
End Function
Private Function GetFormula(p, f, s, c)
'p: path: The drive and path to the closed file (e.g., "d:\files")
'f: file: The workbook name (e.g., "budget.xls")
's: sheet: The worksheet name (e.g., "Sheet1")
'c: cell: The cell reference (e.g., "C4")
'Retrieves a value from a closed workbook
Dim arg As String
'Make sure the file exists
If Right(p, 1) <> "\" Then p = p & "\"
If Dir(p & f) = "" Then
GetFormula = "File Not Found"
Exit Function
End If
'Create the argument
arg = "'" & p & "[" & f & "]" & s & "'!" & _
Range(c).Range("A1").Address(, , xlR1C1).Formula
'Execute an XLM macro
GetFormula = ExecuteExcel4Macro(arg)
End Function
更新:喬爾的第一個後置代號是什麼,我結束了使用,所以我標誌着正確的基礎。這是我使用整行公式的複製粘貼的實際實現。這是最好的,因爲我不知道有多少列可能包含值或公式,可能是C或ZZ。
' silent opening of old file:
Application.EnableEvents = False
Set o = GetObject(FileTextBox.Text)
With Sheets
For r = 2 To NewRowQty ' from second row to last row
ThisCell = "A" & r
o.Worksheets(ThisRate).Range(ThisCell).EntireRow.Copy
Sheets(ThisRate).Range(ThisCell).PasteSpecial xlFormulas
Next r
End With
' Close external workbook, don't leave open for extended periods
Set o = Nothing
Application.EnableEvents = True
從後臺打開工作簿中獲得更多的控制權,可以使用vbscript而不僅僅是vba。加上通過UDF循環檢索值將非常緩慢的一個體面的數據抓取。有關訪問關閉工作簿中的數據的不同方法,請參閱http://stackoverflow.com/q/7524064/641067。根據Tim的評論,您可以禁用事件來停止任何工作簿事件(無論何時運行代碼都是好的做法) – brettdj