excel 将更改保存到新文件中,而不更改原始文件,回滚或编辑新文件?

pkwftd7m  于 2023-06-07  发布在  其他
关注(0)|答案(1)|浏览(204)

我有一个宏,它是用值替换特定颜色单元格中的公式,然后将工作表另存为一个单独的文件。问题-我不希望此更改应用到原始文件。所以,问题是-哪种方式更好,更容易去?要保存工作表然后进行更改,还是在创建新文件后回滚更改?我不太擅长VBA,所以代码可能有点混乱,对不起。

Sub Convertan()
Dim rng As Range
Dim formulaCell As Range
Set rng = ActiveSheet.UsedRange

'Check each colored cell in the range if it has a formula
For Each formulaCell In rng
If formulaCell.HasFormula Then
    If formulaCell.Interior.ColorIndex = 24 Then
    formulaCell.Formula = formulaCell.Value
    
    End If
End If
Next formulaCell

ActiveSheet.Copy ' Copies active sheet to a new workbook
ActiveWorkbook.SaveAs Range("B2").Value

End Sub
neskvpey

neskvpey1#

导出工作表到新工作簿

  • 在新工作簿中创建工作表的副本,并处理该副本,使原始工作表保持不变。
Sub Convertan()
    
    If ActiveSheet Is Nothing Then Exit Sub ' no visible workbooks open
    If Not TypeOf ActiveSheet Is Worksheet Then Exit Sub ' not a worksheet
    
    ActiveSheet.Copy
    
    Dim wb As Workbook: Set wb = Workbooks(Workbooks.Count)
    Dim ws As Worksheet: Set ws = wb.Worksheets(1)
    
    Dim urg As Range, cell As Range
    
    For Each cell In ws.UsedRange.Cells
        If cell.HasFormula Then
            If cell.Interior.ColorIndex = 24 Then
                If urg Is Nothing Then
                    Set urg = cell
                Else
                    Set urg = Union(urg, cell)
                End If
            End If
        End If
    Next cell
    
    If Not urg Is Nothing Then
        Dim arg As Range
        For Each arg In urg.Areas
            arg.Value = arg.Value
        Next arg
        'urg.Interior.ColorIndex = xlNone ' change the color
    End If
        
    Application.DisplayAlerts = False ' overwrite without confirmation
        wb.SaveAs ws.Range("B2").Value
    Application.DisplayAlerts = True
    
    Dim FilePath As String: FilePath = wb.FullName
    
    wb.Close SaveChanges:=False ' just got saved

    MsgBox "Worksheet exported to """ & FilePath & """.", vbInformation

End Sub

相关问题