Vbscript - 获取Excel列索引的问题

时间:2018-06-11 09:19:51

标签: excel vbscript

在创建一个返回excel列索引的简单函数时,我遇到了一个问题,给定了列名。我无法理解为什么脚本表现得如此奇怪(请参阅代码注释以了解问题)。我知道一定有一个愚蠢的错误,但我无法找到它。非常感谢您的帮助!

以下是应该返回Excel工作表中列的索引的函数:

function fn_findColumnIndex(sheetObj, strColumnName)
    Dim i, j, strTemp, intIndex
    j = sheetObj.usedRange.Columns.Count        'will replace it later with better ways to get column count. This works fine for now when I tried to print the value
    intIndex = 0
    for i = 1 to j step 1
        strTemp = sheetObj.cells(1,j).value     'Targeting the values in the 1st row(i.e, the column names)
        'msgbox strTemp                         'when I uncomment this line, all the values in row 1 are displayed as blank. That's the reason the function always return 0. But why are these values blank?
        if strComp(strTemp,strColumnName,1) = 0 then
            intIndex = j
            Exit For
        end if
    next
    fn_findColumnIndex = intIndex
end function

以下是调用上述函数的代码:

set objExcel = createObject("Excel.Application")
objExcel.visible = false
objExcel.displayAlerts = false
strCDPath = "E:\Base\TestDesign\CycleDriver\CycleDriver.xlsx"
Set objBook = objExcel.WorkBooks.Open(strCDPath)
set objSheet = objBook.WorkSheets("CycleDriver")
intRunColumn = fn_findColumnIndex(objSheet,"Run")               'getting the value 0 here. Why?
intModuleColumn = fn_findColumnIndex(objSheet,"Module")         'getting the value 0 here. Why?
intTestScriptColumn = fn_findColumnIndex(objSheet,"TestScript") 'getting the value 0 here. Why?
objBook.close
objExcel.quit

这就是Sheet的样子: enter image description here

1 个答案:

答案 0 :(得分:2)

我不确定vbscript是否支持类似vba的IsError,但如果列标题标签的存在得到保证,我会尝试这样的事情。

intRunColumn = objExcel.match("Run", objSheet.rows(1), 0)
intModuleColumn = objExcel.match("Module", objSheet.rows(1), 0)
intTestScriptColumn = objExcel.match("TestScript", objSheet.rows(1), 0)

由于使用i作为计数器,你自己的功能失败了,

for i = 1 to j step 1

...但是使用j来收集数据,

strTemp = sheetObj.cells(1, j).value
'should be,
strTemp = sheetObj.cells(1, i).value
'also
intIndex = i

所以你总是在UsedRange的右端获得标题标签。