从封闭的Excel文件中抓取公式(不只是值)

我可以通过广泛查找的GetValues函数从封闭的工作簿中获取值; 它效果很好。

但有时我需要从封闭的工作簿中获取单元格的公式。 我试图修改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 (eg, "d:\files") 'f: file: The workbook name (eg, "budget.xls") 's: sheet: The worksheet name (eg, "Sheet1") 'c: cell: The cell reference (eg, "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 (eg, "d:\files") 'f: file: The workbook name (eg, "budget.xls") 's: sheet: The worksheet name (eg, "Sheet1") 'c: cell: The cell reference (eg, "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 

更新:乔尔的第一个代码post是我最终使用的基础,所以我标记的是正确的。 这是我使用整行公式的复制粘贴的实际实现。 这是最好的,因为我不知道有多less列可能包含值或公式,可能是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 

为什么这样令人费解的代码? 由于某种原因,您正在使用的代码正在调用Excel 4.0向后兼容性模式macros处理器。 我无法想象为什么你会这样做。

下面是从c:\ tmp \ book.xlsx的单元格Sheet1!A1中获取公式的一种简单方法:

 Dim o As Excel.Workbook Set o = GetObject("c:\tmp\Book.xlsx") MsgBox o.Worksheets("Sheet1").Cells(1, 1).Formula Set o = Nothing ' this ensures that the workbook is closed immediately 

如果您坚持运行Excel 4样式的macros(在1994年废弃),则需要使用XLM函数GET.FORMULA来检索公式,而不是如下所示的值:

 arg = "GET.FORMULA('" & p & "[" & f & "]" & s & "'!" & _ Range(c).Range("A1").Address(, , xlR1C1) & ")" 

请注意,结果将具有使用R1C1表示法而不是A1表示法的公式。

转换回A1符号(如果你真的想这样做)作为练习留给读者。