将Excel VBA脚本转换为Python

时间:2014-05-08 11:42:50

标签: python vb.net excel vba excel-vba

我有以下VBA脚本:

Sub excelgraphme()
    With ActiveSheet.QueryTables.Add(Connection:= _
        "TEXT;C:\DRIVE D\graphme\result.txt", Destination:=Range("$A$1"))
        .TextFilePlatform = 866
        .TextFileStartRow = 1
        .TextFileParseType = xlDelimited
        .TextFileTextQualifier = xlTextQualifierDoubleQuote
        .TextFileConsecutiveDelimiter = False
        .TextFileTabDelimiter = True
        .TextFileSemicolonDelimiter = False
        .TextFileCommaDelimiter = False
        .TextFileSpaceDelimiter = False
        .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
        .TextFileTrailingMinusNumbers = True
        .Refresh BackgroundQuery:=False
    End With
End Sub

有人可以帮我翻译pywin32吗?首先,我应该怎么做vb语句:WITH END WITH?我怎么翻译呢?

2 个答案:

答案 0 :(得分:3)

似乎你可以使用pywin32库来实现Python。我重写了代码,但不确定TextFileTextQualifier的价值。您可以通过运行VB脚本来查看其值(和其他变量)。

import win32com.client
excel = win32com.client.Dispatch("Excel.Application")

ws = excel.Workbooks.Add().Worksheets(1)
qtNew = ws.QueryTables.Add( "TEXT;C:\\DRIVE D\\graphme\\result.txt", ws.Range("A1"))

qtNew.TextFilePlatform = 866
qtNew.TextFileStartRow = 1
qtNew.TextFileParseType = 1
qtNew.TextFileTextQualifier = 1
qtNew.TextFileConsecutiveDelimiter = False
qtNew.TextFileTabDelimiter = True
qtNew.TextFileSemicolonDelimiter = False
qtNew.TextFileCommaDelimiter = False
qtNew.TextFileSpaceDelimiter = False
qtNew.TextFileColumnDataTypes = [1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]
qtNew.TextFileTrailingMinusNumbers = True
qtNew.Refresh()

答案 1 :(得分:0)

也许更容易看出我是否在没有With And End With语句的情况下重写。因为那样VBA不必检查对象(其方法被调用)是否为Nothing。

Sub excelgraphme()
    Dim qtNew As QueryTable
    Set qtNew = ActiveSheet.QueryTables.Add(Connection:= _
        "TEXT;C:\DRIVE D\graphme\result.txt", Destination:=Range("$A$1"))

    '* is equivalent but slightly slower because With statement means VBA won't check each line for qtNew=Nothing
    qtNew.TextFilePlatform = 866
    qtNew.TextFileStartRow = 1
    qtNew.TextFileParseType = xlDelimited
    qtNew.TextFileTextQualifier = xlTextQualifierDoubleQuote
    qtNew.TextFileConsecutiveDelimiter = False
    qtNew.TextFileTabDelimiter = True
    qtNew.TextFileSemicolonDelimiter = False
    qtNew.TextFileCommaDelimiter = False
    qtNew.TextFileSpaceDelimiter = False
    qtNew.TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
    qtNew.TextFileTrailingMinusNumbers = True
    qtNew.Refresh BackgroundQuery:=False


End Sub