如何根据字符串值将文本添加到相邻的单元格

时间:2019-07-18 17:50:35

标签: excel vba

我目前正在尝试制作一个CSV导入宏系统,该系统可以导入,格式化和简化所包含的数据。至此,我大部分时候已经导入并格式化了文件。此时,我试图在A:A附近添加一列,并基于文件后缀,将相关术语放在新列中。

我尝试使用.Find函数,目前正在尝试使用带有If InStr函数的For循环。

Sub FileExtentionAddition()                                                    

    ActiveSheet.Range("B:B").Select             'Adding the adjacent column
    Selection.Insert Shift:=xlToRight, CopyOrigin:=xlFormatFromLeftOrAbove

    Dim SearchRange As Range, Cell As Range
    Dim i As Integer
    i = 2

    Dim LastRow As String                      'Creates Variable for Last Row
    LastRow = ActiveSheet.UsedRange.Rows.Count       'Defines Last Row Number

    Set SearchRange = Range("A2:A" & LastRow)'Restricts For Loop to used cells

        For Each Cell In SearchRange

            If InStr(1, ActiveCell.Value, ".SLDPRT") > 0 Then
                ActiveCell.Offset(0, 1).Value = "Part"
            ElseIf InStr(1, ActiveCell.Value, ".SLDASM") Then
                ActiveCell.Cell.Offset(0, 1).Value = "Assembly"
            ElseIf InStr(1, ActiveCell.Value, ".SLDDRW") Then
                ActiveCell.Cell.Offset(0, 1).Value = "Drawing"
            Else
                ActiveCell.Offset(0, 1).Value = "Other"
            End If
        Next
End Sub

当前使用文件运行此操作,因此我在B列中添加了0个文本,完全没有错误。我试过使用Debug.Print读取ActiveCell.Value,但据我所知,没有读取任何内容。我是VBA的新手,所以希望我只是想念一些东西。

1 个答案:

答案 0 :(得分:0)

将cell用作变量不是一个好主意,cell已经具有内置的含义。

dim lastrow as long
dim i as long
dim cellval as string

with activesheet ' You should make this an explicit reference
    lastrow = .cells(.rows.count, "A").end(xlup).row
    for i = 2 to lastrow
        cellval = .cells(i, "A").value
        if instr(1, cellval, ".SLDPRT") then
            .cells(i, "B").value = "Part"
        elseif instr(1, cellval, ".SLDASM") then
            .cells(i, "B").value = "ASSEMBLY"
        elseif InStr(1, cellval, ".SLDDRW") Then
            .cells(i, "B").Value = "Drawing"
        else
            .cells(i, "B").value = "Other"
        end if
    next i
end with