如何顺行并在excel中进行计算

时间:2016-07-11 17:31:46

标签: excel vba excel-vba

Private Sub CalculateCharges()
Worksheets("Sheet1").Activate
Dim i As Long
Dim temp As String
RowCount = ActiveSheet.UsedRange.Rows.Count
ActiveSheet.Range("G1").Select
ActiveCell.Offset(1, 0).Select
i = 0
While i < RowsCount
        If ActiveCell.Value Like "*W-M*" Then
        ActiveCell.Offset(0, 8).Value = ActiveCell.Offset(0, 5).Value + ActiveCell.Offset(0, 6).Value
        ActiveCell.Offset(1, 0).Select
        End If
        i = i + 1
Wend
End Sub

以上是我的一段代码。以下是我的excel外观。如果单元格中包含特定的文本值,我如何能够添加2个值

enter image description here

1 个答案:

答案 0 :(得分:0)

您可以简化代码,而无需选择每个单元格,这会使您在大范围内变慢。

您也可以使用InStr功能

Private Sub CalculateCharges()

Dim sht1 As Excel.Worksheet

Set sht1 = ActiveWorkbook.Worksheets("Sheet1")

Dim i As Long
Dim temp As String

RowCount = sht1.UsedRange.Rows.Count

For i = 1 To RowCount
    If sht1.Cells(i, 6).Value Like "*W-M*" Then
    ' can use the InStr function instead
    'If InStr(1, sht1.Cells(i, 6).Value, "W-M", vbTextCompare) > 0 Then
        sht1.Cells(i, 8).Value = sht1.Cells(i, 5).Value + sht1.Cells(i, 6).Value
    End If
Next i

End Sub