簡體   English   中英

使用Excel VBA將單元格的公式轉換為文本

[英]Converting a cell's formula to text using excel vba

我在Excel2003中編寫一個宏,以查找工作簿中所有帶有公式的單元格,並在另一張紙上的幾列中輸出其地址和公式。

我知道我可以使用顯示單個單元格的公式

Public Function ShowFormula(cell As Range) As String

    ShowFormula = cell.Formula

End Function

可以正常工作,但是由於我不想手動查找所有單元格,因此編寫了以下宏來為我查找所有單元格

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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM