问题描述
安装:LibreOffice 7.0.0.3,Win10 2004 19041.450
运行此代码时,出现“未设置对象变量”运行时错误。在LibreOffice调试器中,我可以看到带有正确值的二维数组。我无法访问数组内的单个值。我在做什么错了?
Function test()
Dim objplay As Object
Dim arrTable(1,1) As String,strValue As String
objplay = ThisComponent.Sheets.getByName("Play")
arrTable = objplay.getCellRangeByPosition(0,1,1).getDataArray()
strValue = arrTable(0,0)
End Function
解决方法
不,在调试器中您看不到二维数组,而是一个数组数组-一个数组,每个数组的元素代表范围的一行的值数组。
在getDataArray method的描述中,这称为sequence< sequence< any > >
Function Test
Dim objPlay As Object
Dim arrTable As Variant
Dim strValue As String
objPlay = ThisComponent.getSheets().getByName("Play")
arrTable = objPlay.getCellRangeByPosition(0,1,1).getDataArray()
strValue = arrTable(0)(0)
Rem And don't forget to return the function result
Test = strValue
End Function
,
我也没有被稀疏的 API 文档所启发。我认为必须在调用 getDataArray
之前声明数组的大小/形状。这样做是错误的,因为这样您就无法使用访问元素所需的 arr(0)(0)
语法。
这是一个读-修改-写例程,直到我阅读了 JohnSUN 的解释,我才能开始工作:
Sub RangeArrayTest()
Dim oSheets,inSheet,outSheet,in_range,out_range
Dim range_data As Variant
oSheets = ThisComponent.getSheets()
inSheet = oSheets.getByName("Sheet1")
outSheet = oSheets.getByName("Sheet2")
range_str = "A3:C8"
in_range = inSheet.getCellRangebyName(range_str)
range_data = in_range.getDataArray()
MSgBox(LBound(range_data)) ' prints 0
MSgBox(UBound(range_data)) ' prints 5
MSgBox(LBound(range_data(0))) ' prints 0
MSgBox(UBound(range_data(0))) ' prints 2
for r = 0 to UBound(range_data) ' do something to array
for c = 0 to UBound(range_data(0))
range_data(r)(c) = range_data(r)(c) + 1
next c
next r
out_range = outSheet.getCellRangebyName(range_str)
out_range.setDataArray(range_data)
End Sub