将选定的单元格公式转换为选定工作表中的值

时间:2018-11-20 06:41:30

标签: excel vba selection

我正在使用下面的这段代码将公式转换为单元格,这在一张纸上可以正常工作。但是问题是当我需要将所有位于不同工作表中的选定单元格转换为它们的值时,此代码不会执行此操作。

这是我在Excel中选择单元格的方式: 首先,我选择一个工作表中的单元格,然后右键单击选项卡并选择特定的工作表,然后在Excel中选择每个选定工作表中的相应单元格。

那么关于如何更改此代码以使其在不同的工作表上都能正常工作的任何提示?

Sub formulaToValues()
    If Selection.Cells.Count = 1 Then
        Selection.Value = Selection.Value
        Selection.Cells.Interior.ColorIndex = 0
        Selection.Cells.Font.Color = vbBlack
    Else
        For Each cel In Selection.Cells
            cel.Value = cel.Value
            Selection.Cells.Interior.ColorIndex = 0
            Selection.Cells.Font.Color = vbBlack
        Next cel
    End If
End Sub

3 个答案:

答案 0 :(得分:2)

您应该能够抓住选择的地址,然后将其添加到每个工作表的范围内

Sub formulaToValues()

    Dim celAddr As String
    celAddr = Selection.Address

    Dim ws As Worksheet
    For Each ws In ActiveWindow.SelectedSheets
        With ws.Range(celAddr)
            .Value = .Value
            .Interior.ColorIndex = 0
            .Font.Color = vbBlack
        End With
    Next ws

End Sub

答案 1 :(得分:1)

您正在尝试写入3D单元格集合。我从未见过的一个有趣的问题。我试了一下

以下代码对我有用。我只是添加了一个额外的循环来搜索其他工作表。注意:最好始终声明变量。

答案1:这会循环浏览工作簿中的每张纸

Sub formulaToValues()
Dim cel As Range
Dim ws As Worksheet
If Selection.Cells.Count = 1 Then
    Selection.Value = Selection.Value
    Selection.Cells.Interior.ColorIndex = 0
    Selection.Cells.Font.Color = vbBlack
Else
    For Each ws In ThisWorkbook.Worksheets
        For Each cel In Selection.Cells
            ws.Range(cel.Address).Value = 2 'cel.Value
            Selection.Cells.Interior.ColorIndex = 0
            Selection.Cells.Font.Color = vbBlack
        Next cel
    Next ws
End If

End Sub

Answer2:通过这一操作,它只能遍历所选的工作表

Sub formulaToValues()
Dim cel As Range
Dim ws As Worksheet
If Selection.Cells.Count = 1 Then
    Selection.Value = Selection.Value
    Selection.Cells.Interior.ColorIndex = 0
    Selection.Cells.Font.Color = vbBlack
Else
    For Each ws In ThisWorkbook.Windows(1).SelectedSheets
        For Each cel In Selection.Cells
            ws.Range(cel.Address).Value = 2 'cel.Value
            Selection.Cells.Interior.ColorIndex = 0
            Selection.Cells.Font.Color = vbBlack
        Next cel
    Next ws
End If

End Sub

答案 2 :(得分:0)

非常感谢大家,这很快得到了答复。 我将宏设置为个人宏,因此我结束了

Sub formulaToValues3()
Dim cel As Range
Dim ws As Worksheet
If Selection.Cells.Count = 1 Then
Selection.Value = Selection.Value
Selection.Cells.Interior.ColorIndex = 0
Selection.Cells.Font.Color = vbBlack
Else
For Each ws In ActiveWorkbook.Windows(1).SelectedSheets
    For Each cel In Selection.Cells
        ws.Range(cel.Address).Value = ws.Range(cel.Address).Value 'cel.Value
        Selection.Cells.Interior.ColorIndex = 0
        Selection.Cells.Font.Color = vbBlack
    Next cel
Next ws
End If

End Sub