VBA Excel如何在cell.value =""之前插入新列。每个cel

时间:2016-11-06 23:37:01

标签: excel vba excel-vba

我有一个包含40个单元格的表,其中包含值" total"现在我必须在每个包含Total的单元格之前插入新列。请帮助我绝望。这就是我到目前为止所提供的内容..我不知道如何命令它在整个" 2:2"中执行它,这意味着在您找到第一个Total之后继续这样做直到空单元格。我曾尝试使用Do Until IsEmpty(Active.Cell),但它对我没有任何作用。 HELPP :(

Dim INC As Range
Set INC = Range("2:2").Find("Total")
If INC Is Nothing Then
  MsgBox "Total column was not found."
  Exit Sub
Else
  Columns(INC.Column).Offset(, 0).Resize(, 1).Insert
End If

2 个答案:

答案 0 :(得分:0)

这将在第2行的单元格左侧插入一列,其中总计为值,请注意额外的i = i + 1,因为您需要跳过一个额外的列,因为您刚刚添加了一个:)

Public Sub test()

    Dim ws As Worksheet
    Set ws = Worksheets("Sheet1")

    Dim i As Integer
    i = 1

    Do While (ws.Cells(2, i).Value <> "")

        If (ws.Cells(2, i).Value = "total") Then

            ws.Cells(2, i).EntireColumn.Insert
            i = i + 1

        End If

        i = i + 1

    Loop


End Sub

答案 1 :(得分:0)

OP在显示数据结构后编辑

Option Explicit

Public Sub test()
    Dim f As Range
    Dim firstAddress As String

    With Worksheets("Totals")
        With .Rows(2).SpecialCells(XlCellType.xlCellTypeConstants, xlTextValues)
            Set f = .Find(what:="Total", LookIn:=xlValues, lookat:=xlWhole)
            If Not f Is Nothing Then
                firstAddress = f.Offset(, 1).Address '<-- offset by one column since f will be shifted one column to the right in subsequent statement
                Do
                    f.EntireColumn.Insert
                    Set f = .FindNext(f)
                Loop While f.Address <> firstAddress
            End If
        End With
    End With
End Sub