【问题标题】:delete blue and empty cells from xlsx with vbscript使用 vbscript 从 xlsx 中删除蓝色和空单元格
【发布时间】:2017-10-16 10:43:20
【问题描述】:

我有一个将特定范围的行转换为 csv 文件的 vbscript。
我的问题是它也复制空行而不需要蓝色行。如何在复制之前删除这些完整的空行或从复制中排除它们?
我的代码:

Public Sub xlsToCsv()    
    Const WorkingDir = "C:\Test\"
    Const xlCSV = 24
    Const xlUp = -4162

    Dim fso, SaveName, myFile
    Dim objExcel, objWorkbook, wsSource, wsTarget

    myFile = "source_file.xlsx"
    SaveName = "test.csv"

    With CreateObject("Scripting.FilesystemObject")
        If Not .FileExists(WorkingDir & myFile) Then
            MsgBox "File not found:" & vbCrLf & WorkingDir & myFile, vbInformation, "Script Cancelled"
            WScript.Quit
        End If
    End With

    Set objExcel = CreateObject("Excel.Application")

    objExcel.Visible = False
    objExcel.DisplayAlerts = False

    Set objWorkbook = objExcel.Workbooks.Open(WorkingDir & myFile)
    Set wsSource = objWorkbook.Sheets(1)
    Set wsTarget = objWorkbook.Sheets.Add()

    With wsTarget
    .Cells(1,1).Value = "ID"
    .Cells(1,2).Value = "NAME"
    .Cells(1,3).Value = "DESC"
    End With

    With wsSource
    .Range("F7", .Range("F" & .Rows.Count).End(xlUp)).Copy wsTarget.Range("A2")
    .Range("A7", .Range("A" & .Rows.Count).End(xlUp)).Copy wsTarget.Range("B2")
    .Range("E7", .Range("E" & .Rows.Count).End(xlUp)).Copy wsTarget.Range("C2")
    End With

    objWorkbook.SaveAs WorkingDir & SaveName, xlCSV
    objWorkbook.Close True

    Set objWorkbook = Nothing
    Set objExcel = Nothing
    Set fso = Nothing
    Set myFolder = Nothing
End Sub

call xlsToCsv()

【问题讨论】:

  • 您可以自动筛选空白或蓝色行并将其删除。然后制作你的 CSV。
  • 我不仅需要细胞。如果整行为空,我需要删除一行。我可以过滤吗?如何过滤蓝色单元格?
  • 试过这个命令 "wsSource.Range("A:F").Cells.SpecialCells(xlCellTypeBlanks).EntireRow.Delete" 以错误代码 800A03EC 结束 - 范围对象的特殊单元格属性不能被分配。
  • 它适用于我,没有此错误,请参阅this。请注意,您正在删除整个行,因此如果 A 行中有空白值且 F 中有非空白值,您将丢失 F 中的值

标签: excel vbscript export-to-csv delete-row is-empty


【解决方案1】:
Option explicit

'// Define the blue color here
dim ibluecolor: ibluecolor = 15652797 ' this is 40% Accent1


Public Sub xlsToCsv()    
    Const WorkingDir = "C:\Test\"
    Const xlCSV = 24
    Const xlUp = -4162

    Dim fso, SaveName, myFile, myFolder
    Dim objExcel, objWorkbook, wsSource, wsTarget

    myFile = "source_file.xlsx"
    SaveName = "test.csv"

    With CreateObject("Scripting.FilesystemObject")
        If Not .FileExists(WorkingDir & myFile) Then
            MsgBox "File not found:" & vbCrLf & WorkingDir & myFile, vbInformation, "Script Cancelled"
            WScript.Quit
        End If
    End With

    Set objExcel = CreateObject("Excel.Application")

    objExcel.Visible = False
    objExcel.DisplayAlerts = False

    Set objWorkbook = objExcel.Workbooks.Open(WorkingDir & myFile)
    Set wsSource = objWorkbook.Sheets(1)
    Set wsTarget = objWorkbook.Sheets.Add()

    With wsTarget
        .Cells(1,1).Value = "ID"
        .Cells(1,2).Value = "NAME"
        .Cells(1,3).Value = "DESC"
    End With

    dim Fcol, Acol, Ecol
    With wsSource
        set Fcol = .Range("F7", .Range("F" & .Rows.Count).End(xlUp))
        set Acol = .Range("A7", .Range("A" & .Rows.Count).End(xlUp))
        set Ecol = .Range("E7", .Range("E" & .Rows.Count).End(xlUp))
    End With


    With wsTarget
        Fcol.Copy .Range("A2")
        Acol.Copy .Range("B2")
        Ecol.Copy .Range("C2")
    End With

    dim Frc, Arc, Erc
    Frc = Fcol.Rows.Count
    Arc = Acol.Rows.Count
    Erc = Ecol.Rows.Count

    dim rowcount

    rowcount = Max(Arc, Frc, Erc)

    dim ix
    with wsTarget
        for ix = rowcount + 1 to 2 step -1
            if Len(.cells(ix,1))=0 and len(.cells(ix,2))=0 and len(.cells(ix,3))=0 then
                .rows(ix).delete

            '//Check for blue rows assuming all cells in the row have the same color
            elseif .cells(ix, 1).Interior.Color = iBlueColor then
                .rows(ix).delete
            end if
        next
    End With


    objWorkbook.SaveAs WorkingDir & SaveName, xlCSV
    objWorkbook.Close True

    Set objWorkbook = Nothing
    Set objExcel = Nothing
    Set fso = Nothing
    Set myFolder = Nothing
End Sub

call xlsToCsv()


Function Max(v1, v2, v3)
    select case true
    case v1 => v2 and v1 => v3
        Max = v1
    case v2 => v3
        Max = v2
    case else
        Max = v3
    end select
end function

【讨论】:

  • 这个excel文件有1400行。您的解决方案有效,但需要大约 6 分钟才能完成。你知道的更快吗?
  • 尝试将Appplication.Calculation=xlCalculationManualApplication.Screenupdating=False放在循环之前,然后在循环之后将它们重置为xlCalculationAutomaticTrue
  • 抱歉——我上面的注释应该写的是ObjExcel而不是Application——我想这就是你试过的?
  • 我已经将其更改为 objExcel,因为使用 Application 它不起作用。但它仍然持续大约 6 分钟.. 是这样的常见时间持续还是有更快的方法
【解决方案2】:

这是我原来的另一种方法,旨在提高性能。在这种情况下,VBScript 代码不使用 Excel 创建 csv 文件,而是使用 FileSystemObject 创建的文本文件直接写入 csv 文件。我已经用一组更大的源数据对此进行了测试,它似乎比原来的要快很多——1500 行大约需要 40 秒。打开 Excel 应用程序仍然存在开销(大约 5-10 秒),但您对此无能为力。如果性能对您很重要,您可以进行其他改进。

如果电子表格中有数值,则可能需要进行一些格式化以转换为适合 csv 输出的字符串值,因为 Excel 倾向于对转换为文本的数字使用指数表示法,这并不总是您想要的。我还使用了引号和逗号分隔符,但您可以为 CSV 输出使用不同的格式约定。您可能想要更改 WriteLine 的使用,因为这会在最后一行之后附加一个 CrLf,这可能会被下游解释为一个空白行。

Option explicit

    '// Define the blue color here
    dim ibluecolor: ibluecolor = 15652797 ' this is 40% Accent1

    msgbox "starting"
    call xlsToCsv()
    msgbox "finished"


Public Sub xlsToCsv()    
    Const WorkingDir = "C:\Test\"
    Const xlCSV = 24
    Const xlUp = -4162

    Dim fso, SaveName, myFile, myFolder
    Dim objExcel, objWorkbook, wsSource, wsTarget
    Dim oOutputFile

    myFile = "source_file.xlsx"
    SaveName = "test2.csv"


    With CreateObject("Scripting.FilesystemObject")
        '// Check that the input file exists
        If Not .FileExists(WorkingDir & myFile) Then
            MsgBox "File not found:" & vbCrLf & WorkingDir & myFile, vbInformation, "Script Cancelled"
            WScript.Quit
        End If


        '// Create a text file to be the output csv file
        '//                                             Overwrite v     v False=ASCII format use True for Unicode format
        set oOutputFile = .CreateTextFile( WorkingDir & SaveName, True, False) 


    End With


    Set objExcel = CreateObject("Excel.Application")
    objExcel.Visible = False
    objExcel.DisplayAlerts = False


    Set objWorkbook = objExcel.Workbooks.Open(WorkingDir & myFile)
    Set wsSource = objWorkbook.Sheets(1)

    oOutputFile.WriteLine """ID"",""NAME"",""DESC"""

    '// Get the three column ranges, starting at cells in row 7
    dim Fcol, Acol, Ecol
    With wsSource
        set Fcol = .Range("F7", .Range("F" & .Rows.Count).End(xlUp))
        set Acol = .Range("A7", .Range("A" & .Rows.Count).End(xlUp))
        set Ecol = .Range("E7", .Range("E" & .Rows.Count).End(xlUp))
    End With

    '// Get the number of rows in each column
    dim Frc, Arc, Erc
    Frc = Fcol.Rows.Count
    Arc = Acol.Rows.Count
    Erc = Ecol.Rows.Count

    '// Rowcount is the max row of the three
    dim rowcount
    rowcount = Max(Arc, Frc, Erc)

    dim AVal, FVal, EVal

    dim ix
    for ix = 1 to rowcount
        '// Note - row 1 of each column is actually row 7 in the workbook
        AVal = REPLACE(ACol.Cells(ix, 1), """", """""")
        EVal = REPLACE(ECol.Cells(ix, 1), """", """""")
        FVal = REPLACE(FCol.Cells(ix, 1), """", """""")

        '// Check for an empty row
        if Len(AVal)=0 and len(EVal)=0 and len(FVal)=0 then
            '// skip this row

        '// Check for a blue row
         elseif ACol.cells(ix,1).Interior.Color = iBlueColor then
            '// skip this row

        else 
            '// Write the line to the csv file
            oOutputFile.WriteLine """" & FVal & """,""" & AVal & """,""" & EVal & """"

        end if
    next

    '// Close the output file
    oOutputFile.Close

    '// Close the workbook
    objWorkbook.Close True
    objExcel.Quit

    '// Clean up
    Set oOutputFile = Nothing
    Set objWorkbook = Nothing
    Set objExcel = Nothing
    Set fso = Nothing
    Set myFolder = Nothing

End Sub

Function Max(v1, v2, v3)
    select case true
    case v1 >= v2 and v1 >= v3
        Max = v1
    case v2 >= v3
        Max = v2
    case else
        Max = v3
    end select
end function

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2013-09-01
    • 1970-01-01
    • 2016-10-14
    • 1970-01-01
    • 1970-01-01
    • 2012-11-18
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多