[英]Changing value of a cell based on the value of two cells - VBA Excel
我試圖通過根據該列中的值和另一列中的值更改一列中的單元格值,為電子表格添加一些自動化。 到目前為止我已經得到了下面的代碼。 如果我使用.text,代碼運行良好,但不會更改單元格的值。 如果我使用.value我收到此錯誤消息:
運行時錯誤'13:類型不匹配
請有人可以告訴我這里做錯了什么。
Sub change_orrtime_4()
Application.ScreenUpdating = False
Application.Calculation = xlCalculationManual
'For Each employee In Range("Timesheet_RawData[Employee]")
Dim employee As Range
Dim datefield As Range
Dim tbl As ListObject
Dim tRows As Long
Dim tCols As Long
Dim i As Long
Set tbl = Sheets("Timesheet Data").ListObjects("Timesheet_RawData")
With tbl.DataBodyRange
tRows = .Rows.Count
' tCols = .Colummns.Count
End With
With Sheets("Timesheet Data")
Set employee = Sheets("Timesheet Data").Range("Timesheet_RawData[Employee]")
Set datefield = Sheets("Timesheet Data").Range("Timesheet_RawData[Date]")
End With
With Sheets("Timesheet Data")
For i = 2 To tRows
If employee.Value = "Some Name" And datefield.Value = "1" Then ' type mismatch doesnt occur with .text but then nothing works
employee.Value = "Some Name_SomeTeam"
End If
Next i
End With
Application.ScreenUpdating = True
Application.Calculation = xlCalculationAutomatic
End Sub
您正在將employee
(和datefield
)設置為多個單元格范圍,因此您無法訪問它的Value
屬性,而您可以訪問它將返回Text
屬性,如果所有單元格共享相同的文本或其他Null
所以你必須指向該范圍內的特定單元格,例如:
employee(i).Value
最后你可以按如下方式重構你的代碼:
Sub change_orrtime_4()
Dim employee As Range
Dim datefield As Range
Dim tRows As Long
Dim tCols As Long
Dim i As Long
With Sheets("Timesheet Data")
With .ListObjects("Timesheet_RawData")
With .DataBodyRange
tRows = .Rows.Count
' tCols = .Colummns.Count
End With
Set employee = .ListColumns("Employee").DataBodyRange
Set datefield = .ListColumns("Date").DataBodyRange
End With
For i = 1 To tRows
If employee(i).Value = "Some Name" And datefield(i).Value = "1" Then employee(i).Value = "Some Name_SomeTeam"
Next i
End With
End Sub
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.