vba Excel宏:设置单元格的公式

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/17094000/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-11 21:38:04  来源:igfitidea点击:

Excel Macro: Set the formula of a cell

excelexcel-vbavba

提问by Graham Walters

I'm writing a macro to insert a row into all selected sheets and then set some of the values to equal the values in another sheet. I've managed to insert the row using the following code, but I'm getting stuck trying to set the values. Without a macro, I'd simply enter =InputC7Input being the name of the first sheet in the workbook.

我正在编写一个宏以在所有选定的工作表中插入一行,然后将一些值设置为等于另一个工作表中的值。我已设法使用以下代码插入行,但在尝试设置值时遇到困难。如果没有宏,我只需输入=InputC7Input 作为工作簿中第一个工作表的名称。

Sub InsertRows()
'
' InsertRows Macro
' Inserts rows into all selected sheets at the same position
'

    Dim CurrentSheet As Object

    ' Loop through all selected sheets.
    For Each CurrentSheet In ActiveWindow.SelectedSheets
        ' Insert 1 row at row 7 of each sheet.
        CurrentSheet.Range("a7:a7").EntireRow.Insert
        CurrentSheet.Range("c7").Value =Input!C7 'this is not working
    Next CurrentSheet
End Sub

回答by Ripster

If you just want the value from the sheet named "Input" you can do this:

如果您只想要名为“输入”的工作表中的值,您可以这样做:

CurrentSheet.Range("C7").Value = Sheets("Input").Range("C7").Value

If you want the formula "=Input!C7" you can do this:

如果你想要公式“=Input!C7”,你可以这样做:

CurrentSheet.Range("C7").Formula = "=Input!C7"

回答by stenci

You need to use the Formulainstead of the Valueproperty, and the text should be quoted:

您需要使用Formula代替Value属性,并且应该引用文本:

CurrentSheet.Range("c7").Formula "=Input!C7"