如何以编程方式从excel 2010中删除行

时间:2015-12-12 06:15:43

标签: excel vb6

我有一个.xls文件。我会逐行浏览文件并删除我不需要的行。出于某种原因,在找到要删除的行之后,我无法删除它。这应该很简单,但我还没有能够让它为我工作。

我已经尝试了

  • 范围(" 1:2")。剪切(仅作为示例)
  • ' objWS.Rows(iCtr)=""
  • 列表项
  • 列表项
  • .Application.ActiveSheet.UsedRange.Row.Delete
  • 列表项
  • theDelRange.EntireRow.Delete

认为该文件可能被阻止(显然与受保护的文件不同)我尝试了以下内容:

  • objExcel.ActiveSheet.protected = False
  • 设置.Application.ActiveProtectedViewWindow.Edit = True(带 protected set as true)

所有这些运行都没有错误,它们只是不删除.xls文件中的任何行。

这是我的代码段

theProgramFilesPath = GetProgramFilesPath
Set objExcel = New Excel.Application
Set objWB = objExcel.Workbooks.Add
Set objWS = objWB.Worksheets(1)

objExcel.Workbooks.Open theVendorPricesFilePath
objExcel.ActiveSheet.protected = False
objExcel.Application.DisplayAlerts = False
objExcel.Application.Calculation = False

With objExcel 
.Application.ScreenUpdating = False     
    Set .Application.ActiveProtectedViewWindow.Edit = True        
    LineCnt = .Application.ActiveSheet.UsedRange.Rows.Count
    ColCnt = .Application.ActiveSheet.UsedRange.Columns.Count

    For iCtr = LineCnt To 1 Step -1
        tempTxt = .Cells(iCtr, 9).Value
        If Val(tempTxt) = 0 Then   (Here's where I need to delete the row)
            'theDelRange = .Range(.Cells(iCtr, 1), .Cells(iCtr, 10))        '.EntireRow.Delete)
            'theDelRange.EntireRow.Delete
            '.Application.ActiveSheet.UsedRange.Row.Delete
            'objWS.Rows(iCtr) = ""
            'Range("1:2").Cut
        End If            
    Next
.Application.ScreenUpdating = True
End With

这么简单的事......叹了口气。任何帮助真的很感激。

1 个答案:

答案 0 :(得分:0)

我认为问题在于您没有引用包含您要检查的数据的工作表对象并删除目标行。

在您的代码段中,您从with objExcel开始,这是一个Excel实例,然后您没有引用Workbook,然后引用worksheets("index")(存在于第一行中)您的代码objWS。)

    With objExcel 
    .Application.ScreenUpdating = False     
    Set .Application.ActiveProtectedViewWindow.Edit = True        
    LineCnt = .Application.ActiveSheet.UsedRange.Rows.Count
    ColCnt = .Application.ActiveSheet.UsedRange.Columns.Count

    For iCtr = LineCnt To 1 Step -1
        tempTxt = .Cells(iCtr, 9).Value
        If Val(tempTxt) = 0 Then   (Here's where I need to delete the row)
            'theDelRange = .Range(.Cells(iCtr, 1), .Cells(iCtr, 10))        '.EntireRow.Delete)
            'theDelRange.EntireRow.Delete
            '.Application.ActiveSheet.UsedRange.Row.Delete
            'objWS.Rows(iCtr) = ""
            'Range("1:2").Cut
        End If            
    Next
.Application.ScreenUpdating = True
End With

因此,您应该尝试使用该对象,如下所示:

For iCtr = LineCnt To 1 Step -1
        with objWS
               tempTxt = .Cells(iCtr, 9).Value
               If Val(tempTxt) = 0 Then   (Here's where I need to delete the row)
                theDelRange = .Range(.Cells(iCtr, 1), .Cells(iCtr, 10)) 'I suppose that here
               ' you have declared theDelRange as a Range object ;)      
                theDelRange.EntireRow.Delete

                End If
        End With


    Next