2017-08-03 277 views
1

我正在嘗試編寫一個簡單的VBA宏,它將採用活動單元格的列和用戶的輸入將一行單元格範圍添加到一起。範圍是通過將用戶輸入的整數添加到活動列並且是結束列來計算的。問題是,當我運行它時,它給了我一個「編譯錯誤:無效的限定符」,並在'總'行中生氣。VBA宏編譯錯誤

這是我的代碼。我剛剛開始使用VBA,但不能那麼辛苦......對吧?

Sub Food() 
Dim first As Variant 
Dim last As Integer 
Dim days As Integer 
Dim month As Range 
Dim total As Double 
first = ActiveCell.Column 
days = InputBox("Days in the month?") 
last = first + days 
Set month.Value = Range(Cells(first, 4), Cells(last, 4)) 
total.Value = WorksheetFunction.Sum(month) 
Worksheets(1).Cells(1, 13).Value = total 
End Sub 

回答

0

看起來像一個語法錯誤。嘗試放下monthtotal上的.value

Sub Food() 
Dim first As Variant 
Dim last As Integer 
Dim days As Integer 
Dim month As Range 
Dim total As Double 
first = ActiveCell.Column 
days = InputBox("Days in the month?") 
last = first + days 
Set month = Range(Cells(first, 4), Cells(last, 4)) 
total = WorksheetFunction.Sum(month) 
Worksheets(1).Cells(1, 13).Value = total 
End Sub 

如果你想獲得一定範圍內的值到一個變量,你把.value與範圍,而不是變量。例如:

x = cells(1,2).value 

.value屬性返回的範圍對象的值。所以在函數上使用它並沒有任何意義,如果你嘗試,會導致excel拋出錯誤。嘗試將month變量設置爲值而不是範圍也沒有意義,因爲這會使其成爲數組。如果你想month是一個數組,你會希望將它設置爲一個變體而不是範圍。

有關.value屬性的詳細信息,請參閱以下鏈接: https://msdn.microsoft.com/en-us/vba/excel-vba/articles/range-value-property-excel