2016-10-02 92 views
0

我正在編寫一個VBA代碼來對Excel進行一些計算。 我有一個數字單元格,我希望另一個單元格有公式基於第一個,而不是公式的計算值。我一直在使用.Formula努力,但它不工作:在VBA中添加公式表達式而不是值宏excel代碼

'Ciclo 
Cells(rowWhereToAddPhase, 6).Value = Round(3600/Worksheets(originalSheet.Name).Cells(row, 22), 2) 

'Prod/h 
Cells(rowWhereToAddPhase, 7).Formula = "=Round(60/Cells(rowWhereToAddPhase, 6).Value * 60, 0)" 

當我嘗試這個,我只是得到錯誤400

相反,如果我用這個:

'Prod/h 
Cells(rowWhereToAddPhase, 7).Value= Round(60/Cells(rowWhereToAddPhase, 6).Value * 60, 0) 

我只是得到一個普通的數字。

圖片,它的外觀在第二種情況:

enter link description here

我怎麼想擁有它:

enter link description here

我想象中的問題是,如何調用cell:我使用Cells(**rowWhereToAddPhase**, 6)來引用它,因爲我不知道它在哪一行,但我想我應該用另一種方式。

任何想法?

由於

回答

2
Cells(rowWhereToAddPhase, 7).Formula = _ 
    "=Round(60/" & Cells(rowWhereToAddPhase, 6).Address() & "*60,0)" 
0

.Formula必須是一個字符串,其內容是一樣的,當你在Excel中手動輸入的公式(例如oRange.Formula = 「= SUM(A5:C7)」)。

嘗試手動在Excel單元格中創建公式。然後當它工作時,通過VBA設置它,也許使用一些字符串連接來獲取變量rowWhereToAddPhase。