-1

如果该列中不包含单个值,是否有使用 vb 脚本删除 Excel 列的更快过程?

   For Task=2 To 300

   Vcounter="False"
   IntRow6=2

   Do While objSheet6.Cells(IntRow6,1).Value = ""

  If objSheet6.Cells(IntRow6,Task).Value <> "" Or objSheet6.Cells(IntRow6,Task).Value <> "None"


   Vcounter="True"
   Exit DO

  End If

 IntRow6=IntRow6+1
 Loop

  If  Vcounter <> "True" Then

   objSheet6.Cells(1,Task).EntireColumn.Delete

  End If

 Next

更新:

您还可以说如何计算 Excel 每一行中的数据数吗?例如

        Col1   Col2  Col3   Col4   Col5

  Row1   A       B            X     P
  Row2   L       M
  Row3                 T            V

现在 VBScript 应该给我 Row1 包含 4 个数据,Row2 包含 2 个数据和 Row3 包含 2 个数据的计数。

代码更新

我已经参考您的代码更新了我的代码。并使用“Hi”作为弹出框,查看控件是否进入了If Body。但弹出框始终没有出现。调用“Application.WorksheetFunction.CountBlank(rg)”中似乎发生了一些错误。你能在这里检查并帮助我吗?没有一列被删除,它们应该在哪里。

Sub DeleteColumns(Ob6)
     Dim CountBlank 
     Dim rows 
     Dim rg,c
  Set objExcel1 = CreateObject("Excel.Application")

 For c = 150 To 155
    Set rg = Ob6.Range(Ob6.Columns(c),Ob6.Columns(c))
    CountBlank = objExcel1.Application.WorksheetFunction.CountBlank(rg)
    rows = rg.rows.Count

    If CountBlank = rows Then
        MsgBox("Hi")
        rg.EntireColumn.Delete
    End If
 Next
End Sub

修复:我刚刚修复了它。所以这里没有问题。只需要您对更新部分的帮助。

谢谢

4

2 回答 2

2

您可以使用在 Application.WorksheetFunction 中找到的函数 CountBlank

Dim CountBlank As Long
CountBlank = Application.WorksheetFunction.CountBlank(Range("A:A"))

然后,您只需将其与同一范围内的行数进行比较:

Dim ws As Worksheet
Dim rows As Long
Set ws = ThisWorkbook.Worksheets(1)
rows = ws.Range("A:A").Count

从索引 1 到 300 删除空列的整个代码如下所示:

Sub DeleteColumns()
    Dim CountBlank As Long
    Dim ws As Worksheet
    Dim rows As Long
    Set ws = ThisWorkbook.Worksheets(1)
    Dim rg As Range

    For c = 1 To 300
        Set rg = Range(ws.Columns(c), ws.Columns(c))
        CountBlank = Application.WorksheetFunction.CountBlank(rg)
        rows = rg.rows.Count

        If CountBlank = rows Then
            rg.EntireColumn.Delete
        End If
    Next
End Sub
于 2012-12-11T13:19:57.507 回答
0

你的想法很完美,除了我在代码中做了一些改变。我们需要使用 Decrement For 循环,而不是 Increment 循环。否则,Delete 函数不会删除所有列。这里更改和更新的代码是:

Sub DeleteColumns(Ob6)
  Dim CountBlank 
  Dim rows 
  Dim rg,c

  For c = 155 To 150 step - 1
    Set rg = Ob6.Range(Ob6.Columns(c),Ob6.Columns(c))
    CountBlank = objExcel1.Application.WorksheetFunction.CountBlank(rg)
    rows = rg.rows.Count
         'MsgBox("CountBlank:"&CountBlank)
         'MsgBox("Count:"&rows)
    If CountBlank = (rows-1) Then ' Rows-1 means the count should start from the 2nd row onward

        rg.EntireColumn.Delete

    End If
 Next

End Sub
于 2012-12-12T04:43:32.290 回答