读取字符串值并关闭COM对象时,该值有时会失效

时间:2014-11-21 15:17:28

标签: excel vbscript com

简短说明

当我从Excel读取值时,该值有时无效。你能详细解释一下是什么吗? 正好进行?

详细说明

我读取了单元格A1的值并将其存储在s和字典oDict中。取决于是否 我关闭Excel(oExcel.Quit)字典中的值似乎无效(而VarType报告vbObject代替 vbString)。

当我用版本B或版本C替换存储的值时,似乎复制了值(?),最终的VarType现在报告vbString

我很欣赏详细说明原因。

感谢您的考虑。

最小的测试用例

(需要在单元格A1处具有值的excel文件)

Option Explicit

Dim oExcel
Set oExcel = CreateObject("Excel.Application")

oExcel.Workbooks.Open "C:\Temp\Excel.xlsx"

Dim oWorkSheet
Set oWorkSheet = oExcel.ActiveWorkbook.Worksheets(1)

Dim s
s = oWorkSheet.Cells(1, 1)

Dim oDict
Set oDict = CreateObject("Scripting.Dictionary")

oDict.Add 1, oWorkSheet.Cells(1, 1)           ' version A
'oDict.Add 1, ""&oWorkSheet.Cells(1, 1)       ' version B
'oDict.Add 1, CStr(oWorkSheet.Cells(1, 1))    ' version C

WScript.Echo VarType(s) & ", " & VarType(oDict(1)) ' prints 8 (vbString), 8 (vbString)

oExcel.Workbooks(1).Close
oExcel.Quit

WScript.Echo VarType(s) & ", " & VarType(oDict(1)) ' prints 8 (vbString), 9 (vbObject)

参考

0 个答案:

没有答案