我的目標是嘗試遍歷Excel 2010工作表中的一組單元格,並在同一工作表中更改另一個單元格的值。這是我試圖用VBA做到這一點的嘗試。當我嘗試更改moCost定義的單元格時,出現「Type MisMatch」錯誤。嘗試使用VBA更改工作表中特定單元格的值失敗
另外,我假設當我更改(使用工作表更改事件)我的工作表的單元格中的任何一個變量的值我使用設置它將更改moCostAfford si的值更正?只是想確認。
任何幫助/方向將不勝感激。
這裏是我的代碼:
Private Sub Worksheet_Change(ByVal Target As Range)
If Not Intersect(Target, Me.Range("I4:K42")) Is Nothing Then
On Error GoTo haveError
Application.EnableEvents = False
Dim moCost As Range, moCostAmount As Range, moCostManual As Range, moCostAfford As ValueChange
Dim cell As Range, affordabilityRowValues As Range
Set moCost = Range("A13")
Set moCostAmt = Range("B13")
Set moCostManual = Range("B14")
Set moCostAfford = Range("C13")
Set affordabilityRowValues = Intersect(Target, Me.Range("I4:K42"))
For Each cell In affordabilityRowValues.Cells
If cell.Offset(0, 1) = moCost And cell.Offset(0, 2) = moCostAmount And moCostManual = "0" Then
moCostAfford = cell.Offset(0, 3).Value
Else
moCostAfford = moCostAmount
End If
Next
Set affordabilityRowValues = Nothing
Set moCostAfford = Nothing
Set moCostManual = Nothing
Set moCostAmount = Nothing
Set moCost = Nothing
Application.EnableEvents = True
End If
Exit Sub
haveError:
MsgBox Err.Description
Application.EnableEvents = True
End Sub
先握住東西,在模塊的頂部鍵入Option Explicit。這會警告你任何你沒有聲明或拼錯的變量(提示:至少有一個)。之後,檢查變量類型和您用於moCostAffordValue的屬性。我從來沒有使用ValueChange類型,但它顯示值不是該類型的有效屬性或期望的參數。 – Dave 2014-10-31 13:28:48
'moCost'是一個範圍,但你沒有在行中設置一個範圍'Set moCost = Application.Cells.Value(「A13」)'看起來像'Set moCost = Range(「A13」)'或者' A13'有一個單元格地址,然後'Set moCost = Range(Range(「A13」)。Value)'類似於其他 – 2014-10-31 13:36:36
謝謝,夥計們!我會做出這些更正,並希望消除錯誤。 – Melinda 2014-10-31 13:40:48