基于两个单元格的值更改单元格的值 – VBA Excel

我试图通过改变一列中的单元格的值,基于该列中的值和另一列中的值来添加一些电子表格的自动化。 到目前为止,我已经得到了下面的代码。 如果我使用.text代码运行良好,但不改变单元格的值。 如果我使用.value我得到这个错误消息:

运行时错误'13:types不匹配

请有人build议我在这里做错了。

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属性,如果所有单元格共享相同的文本或否则返回一个文本

所以你必须指出在该范围内的特定单元格,如:

 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