繁体   English   中英

根据两个单元格的值更改单元格的值 - VBA Excel

[英]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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM