将Excel宏转换为vbscript

时间:2014-09-16 20:33:51

标签: excel csv vbscript

你好,我有一个问题。

我有一个csv文件,其中包含我不想要的所有数据。 所以我想删除它。我是vbs脚本的新手,所以需要一些帮助。

如何在vbs脚本中编写此内容?

Sub Work1()
'
' Work1 Makro
'

'
    Columns("A:A").Select
    Selection.Delete Shift:=xlToLeft
    Columns("B:D").Select
    Selection.Delete Shift:=xlToLeft
    Columns("C:H").Select
    Selection.Delete Shift:=xlToLeft
    Columns("E:E").Select
    Selection.Delete Shift:=xlToLeft
    Columns("F:F").Select
    Columns("F:AP").Select
    Selection.Delete Shift:=xlToLeft
    Range("A1:E7").Select
    Selection.EntireRow.Delete
    Selection.Replace What:=",", Replacement:=".", LookAt:=xlPart, _
        SearchOrder:=xlByRows, MatchCase:=False, SearchFormat:=False, _
        ReplaceFormat:=False
    Range("N23").Select
    ActiveWindow.SmallScroll Down:=-21
    ChDir "C:\CSV"
    ActiveWorkbook.SaveAs Filename:="C:\CSV\export.csv", FileFormat:=xlCSV, _
        CreateBackup:=False
End Sub

我已经走到了这一步。这部分删除了我的问题列。

Set xl = CreateObject("Excel.Application") 
xl.Visible = True  'set to False for production 

Set wb = xl.Workbooks.Open("C:\csv\prov.csv")
Set objWorkbook = wb


‘replace values

Const FromValue = ","
Const ToValue = "."

Dim objExcel
Dim objWorksheet : Set objWorksheet = objWorkbook.Worksheets(1)
'Dim objRange : Set objRange = objWorksheet.UsedRange

objWorksheet.Cells.Replace FromValue, ToValue

objExcel.DisplayAlerts = False 


wb.SaveAs "C:\csv\data.csv"
wb.Close SaveChanges=True

2 个答案:

答案 0 :(得分:0)

您可以将Select和以下Selection语句合并为一个。例如,而不是:

Columns("E:E").Select
Selection.Delete

你可以这样做:

objWorksheet.Columns("E:E").Delete
' or
objWorksheet.Columns("E").Delete
' or
objWorksheet.Columns(5).Delete

这将从objWorksheet引用的工作表中删除E列。

答案 1 :(得分:0)

你好thnak yuou快速回答。 这很棒,这是最终的脚本。



Set xl = CreateObject("Excel.Application") 
xl.Visible = True  'set to False for production 
 
Set wb = xl.Workbooks.Open("C:\csv\prov.csv")
set objWorksheet = xl
Set objExcel = xl

objWorksheet.Columns("A:A").Delete
objWorksheet.Columns("B:D").Delete
objWorksheet.Columns("C:H").Delete
objWorksheet.Columns("E:E").Delete
objWorksheet.Columns("F:AP").Delete
objWorksheet.Rows("1:7").Delete

Const FromValue1 = ","
Const ToValue1 = "."


Dim objExcel
Dim objWorksheet : Set objWorksheet = xl
'Dim objRange : Set objRange = objWorksheet.UsedRange
 
objWorksheet.Cells.Replace FromValue1, ToValue1

	
objExcel.DisplayAlerts = False 

wb.SaveAs "C:\csv\export.csv"
wb.Close SaveChanges=True

xl.Quit