2015-08-28 18 views
0

我正在编写一个VbScript来删除通过参数放入的Excel文件中的特定列。 excel文件的第1行是列的标题。这是我当前的代码,用于在标题中查找特定的字符串。VbScript搜索特定标题并选择整个列

Set objExcel = CreateObject("Excel.Application") 
If WScript.Arguments.Count = 0 Then 
    WScript.Echo "Drop excel files on this script" 
Else 
    objExcel.Visible = True 
    objExcel.Workbooks.Add(WScript.Arguments.Item(0)) 
    Set FoundCell = objExcel.Range("A1:C1").Find("Sales Figures") 

    '* Select the entire column of FoundCell and remove it 

End If 

我的第一个问题是,我必须手动指定要搜索的标题范围(A1:C1)。有没有办法自动执行(A1:X1) - 其中X是Excel表格中的最后一列。

2,我如何删除整个FoundCell列?

回答

1

我认为这可能有帮助。您可以使用Sheet对象的UsedRange属性来仅选择具有数据的单元格。这意味着你不需要明确列引用。

Cells(1)Find()限制为UsedRange的第一行。

我在最后添加的位只是为了正确关闭Excel。

Option Explicit 

dim objExcel, book, FoundCell 
Set objExcel = CreateObject("Excel.Application") 
If WScript.Arguments.Count = 0 Then 
    WScript.Echo "Drop excel files on this script" 
Else 
    objExcel.Visible = True 
    set book = objExcel.Workbooks.Add(WScript.Arguments.Item(0)) 
    ' assume we're looking in the activesheet 
    Set FoundCell = book.ActiveSheet.UsedRange.Cells(1).Find("Sales Figures") 

    if not IsNull(FoundCell) then 
     '* Select the entire column of FoundCell and remove it 
     book.ActiveSheet.UsedRange.Columns(FoundCell.Column).Delete 
     ' book.SaveAs "removed.xlsx" 
    end if 

End If 
' close up avoiding any "save changes?" dialog 
for each book in objExcel.Workbooks 
    book.saved = true 
next 
objExcel.quit