用VBA遍历Excel中的数据

by Weijie JIN on

前段时间做一个数据导入的东西,数据源是excel,里面数据不太工整,需要对于所有行进行一定的操作。
请教了一下同事,写了一点vba代码处理excel,代码比较简单,就不作太多的说明了,看注释足以 :)

Const START_ROW = 1
Const END_ROW = 3000

'目标列
Const COL_TARGET = 1
'数据源列
Const COL_SOURCE = 2

'指定要处理哪个sheet
Const TARGET_SHEET = "Sheet1"

Public Sub MERGEROWS()
    Dim s As Worksheet

    Set s = ThisWorkbook.Sheets(TARGET_SHEET)

    Dim i As Integer

    Dim result As String

    '作一次循环遍历所有行
    Dim resultRow As Integer
    resultRow = 1
    result = Trim(s.Cells(1, COL_TARGET).Text)
    For i = START_ROW To END_ROW Step 1
        Dim name As String
        name = Trim(s.Cells(i, COL_SOURCE).Text)
        If name = "" Then
            result = result + Trim(s.Cells(i, COL_TARGET).Value)
            s.Cells(i, COL_TARGET).Value = ""
        Else
            s.Cells(resultRow, COL_TARGET).Value = result
            result = Trim(s.Cells(i, COL_TARGET).Value)
            resultRow = i
        End If

    Next

End Sub  

Previous post:

Next post: