使用excel vba将单元格的公式转换为文本

我在Excel2003中编写一个macros来查找工作簿中所有带有公式的单元格,并在不同的工作表中输出其地址和公式。

我知道我可以显示使用单个单元格的公式

Public Function ShowFormula(cell As Range) As String ShowFormula = cell.Formula End Function 

这工作得很好,但因为我不想手工find所有的细胞,所以我写了下面这个macros来为我find它们

 Sub Macro2() Dim i As Integer Dim targetCells As Range Dim cell As Range Dim referenceRange As Range Dim thisSheet As Worksheet Set referenceRange = ActiveSheet.Range("CA1") With referenceRange For Each thisSheet In ThisWorkbook.Sheets If thisSheet.Index >= referenceRange.Parent.Index Then Set targetCells = thisSheet.Cells.SpecialCells(xlCellTypeFormulas, 23) For Each cell In targetCells If cell.HasFormula Then .Offset(i, 0).Value = thisSheet.Name .Offset(i, 1).Value = cell.Address .Offset(i, 2).Value = CStr(cell.Formula) i = i + 1 End If Next End If Next End With End Sub 

它发现所有单元格都很好,但不是将公式显示为文本,而是显示公式结果。

我错过了什么输出公式作为文本而不是公式?

尝试这个:

 .Offset(i, 2).Value = "'" & CStr(cell.Formula) 

而且,这会让事情变得更快一点。 代替

 For Each thisSheet In ThisWorkbook.Sheets If thisSheet.Index >= referenceRange.Parent.Index Then 

尝试

 For j = referenceRange.Parent.Index to Sheets.Count Set thisSheet = Sheets(j)