首页 > 解决方案 > 使用 VBScrip 将公式替换为 Excel 中的结果值

问题描述

我正在尝试替换 excel 电子表格中的所有公式,同时保持其他所有内容不变。使用 VBA 设法做到这一点,但找不到使用 Vbscript 的方法。

宏的使用不是一个选项,因为它们在默认情况下被禁用,目标是在没有人工干预的情况下更新 excel 文件。

这是我尝试过的代码(最新尝试),它将公式的结果复制为值,但没有从原始工作表中获取任何其他内容(丢失所有图形对象和格式)。

function create_daily_dash()
    dim i
    dim current_sheet
    outputFiletype = 51 'type_xlsx

    inputFilename = myExcelFile
    outputFilename = path & newfilename

    Set objExcel = CreateObject("Excel.Application")
    objExcel.DisplayAlerts = False

    Set currentWorkbook = objExcel.Workbooks.Open(inputFilename)
    Set newWorkbook = objExcel.Workbooks.Add()

    i = 0
    For Each current_sheet In currentWorkbook.Worksheets
        If current_sheet.Visible Then 
            i = i + 1

            Dim new_sheet
            If newWorkbook.Sheets.Count < i Then
                newWorkbook.Sheets.Add , newWorkbook.Sheets(i-1)
            End If
            Set new_sheet = newWorkbook.Sheets(i)
            new_sheet.Name = current_sheet.Name

            current_sheet.UsedRange.Copy
            new_sheet.Select
            new_sheet.UsedRange.PasteSpecial -4163
        End If
    Next
    newWorkbook.SaveAs outputFilename, outputFiletype
    currentWorkbook.Close False
    newWorkbook.Close False
    objExcel.Quit
end function

标签: excelvbscript

解决方案


Managed to get a way to replace the formulas with the corresponding values but it does it extremely slowly.

It' just a loop that goes through the interval of cells I want to update and replaces the formula with the value one cell at a time.

Am sure there's a better way to do this but can't find anything. This is the code I'm using:

for i=1 to ColNo 
    for j=1 to RowNo
        curr_sheet.Cells(i,j).value = curr_sheet.Cells(i,j).value
    next
next

Any tips on how to get the same result more efficiently are very welcome.


推荐阅读