Excel模板 - 在创建文件时仅评估一次函数

时间:2018-02-22 21:10:11

标签: excel excel-formula

我们的簿记员有一个Excel模板,用于创建新的采购订单。她希望这样做,以便当她从这个模板创建一个新的电子表格时,它只会在采购订单号单元格中生成一个新的随机数。

为了尽量减少两个订单号相同的可能性,我考虑使用时间戳作为种子而不是实际的随机数,如下所示:=(NOW()-DATE(1970, 1, 1)) * 864(我知道这不会成为一个正确的Unix时间戳,因为这并不重要,我只是希望它更短。)

我的主要问题是,当从这个模板创建新文件时,如何将公式放入单元格并确保它只评估一次?

1 个答案:

答案 0 :(得分:0)

您应该能够修改和使用的示例代码:

Sub tgr()

    Dim wb As Workbook
    Dim wbNew As Workbook       'Only used if copying template sheet to a brand new workbook
    Dim wsTemplate As Worksheet
    Dim wsNew As Worksheet

    Set wb = ActiveWorkbook
    Set wsTemplate = wb.Sheets("Template")  'Change this to the actual name of your template worksheet

    'If copying the template to a new sheet in same workbook
    wsTemplate.Copy After:=wb.Sheets(wb.Sheets.Count)
    Set wsNew = ActiveSheet

    'If copying the template to a brand new workbook, leave commented out if not using
    'Set wbNew = Workbooks.Add
    'wsTemplate.Copy Before:=wbNew.Sheets(1)
    'Set wsNew = wbNew.ActiveSheet
    'Code here to remove blank sheets from the new workbook if desired

    'wsNew.Name = "Actual Sheet Name"    'Update the name of this newly created sheet
    With wsNew.Range("A1")  'Change to the actual cell that needs to only have its calculation occur once
        .Calculate                      'Update the calculation
        .Value = .Value                 'Convert so that the cell only shows its value and is no longer a formula
    End With

End Sub