vbscript在xlsx文件中为范围命令

时间:2017-10-09 08:54:22

标签: excel vbscript range row

我编写了一个vbscript来将特定范围的xlsx文件保存到csv文件中。 我想选择不是彼此相邻的不同列。每列的范围应包含其内容为最后一行(范围("F6").End(xlToRight)) 我的代码:

Public Sub xlsToCsv()    
    Const WorkingDir = "C:\"
    Const xlCSV = 6

    Dim fso, SaveName, myFile
    Dim objExcel, objWorkbook, sheet

    myFile = "test.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)

    With objWorkbook.Sheets(1)
            .Range("D87", .Range("D87").End(-4121)).Copy
             objWorkbook.Sheets.Add().paste
            .Range("E87", .Range("E87").End(-4121)).Copy
    End With

    set sheet =  objWorkbook.Sheets.Add()
    sheet.paste
    objWorkbook.SaveAs WorkingDir & SaveName, 23
    objWorkbook.Saved = true
    objWorkbook.Close

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

call xlsToCsv()

我在第18行代码800A000D中遇到类型冲突,其中包含'范围'。
我怎样才能做到这一点?

2 个答案:

答案 0 :(得分:2)

这里有两件事:

  • 每当使用Range对象Range("F6").End(xlToRight)时,都需要提及其类型/父对象。因此,在您的情况下,应将其替换为objWorkbook.Sheets(1).Range("F6").End(xlToRight)

  • VBScript不知道xlToRight的含义。因此,您必须使用xlToRight的值-4161,如下所示:

替换以下代码:

objWorkbook.Sheets(1).Range("F6", Range("F6").End(xlToRight)).Copy
objWorkbook.Sheets(1).Range("C6", Range("C6").End(xlToRight)).Copy

。通过

 With objWorkbook.Sheets(1)
     .Range("F6", .Range("F6").End(-4161)).Copy
     .Range("C6", .Range("C6").End(-4161)).Copy
 End With

答案 1 :(得分:1)

认为您的某些代码可能会丢失,例如WorkingDir的声明。 我通过添加:使用objWorkbook.Sheets(1)

显式引用了范围
    Dim WorkingDir As String

    WorkingDir = "C:\test.xlsx"

    Dim fso, FileName, SaveName, myFile
    Dim objExcel, objWorkbook

    Set fso = CreateObject("Scripting.FilesystemObject")
    Set myFile = fso.GetFile(WorkingDir)

    Set objExcel = CreateObject("Excel.Application")

    objExcel.Visible = False
    objExcel.DisplayAlerts = False

    'main operation
    FileName = Left(myFile, InStrRev(myFile, "."))
    Set objWorkbook = objExcel.Workbooks.Open(myFile)

    With objWorkbook.Sheets(1)
       .Range("F6", .Range("F6").End(xlToRight)).Copy
       .Range("C6", .Range("C6").End(xlToRight)).Copy
    End With

    Dim sheet: Set sheet = objWorkbook.Sheets.Add()

    sheet.Paste
    SaveName = FileName & "csv"
    objWorkbook.SaveAs SaveName, 23
    objWorkbook.Saved = True
    objWorkbook.Close

    Set objWorkbook = Nothing
    Set objExcel = Nothing
    Set fso = Nothing
   ' Set myFolder = Nothing