目前我有一个用户定义的函数,它运行几个涉及矩阵生成的例程.要检查这些矩阵是否已正确生成,我想将它们放在工作表上.用户定义的函数工作正常,我已经在我想要找出数组中的内容的地方添加了以下内容:
Call CheckArray(TestArray)
上面的’TestArray’取决于我想看的数组.
‘CheckArray’子程序如下:
Sub CheckArray(MyArray As Variant)
MatrixRows = UBound(MyArray, 1)
MatrixCols = UBound(MyArray, 2)
MsgBox MyArray(11, 2)
MsgBox "Matrix size = " & MatrixRows & " rows x " & MatrixCols & " columns"
ActiveWorkbook.Worksheets("Check array").[A1].Resize(MatrixRows, MatrixCols) = MyArray
End Sub
请注意,我在那里放置了两个MsgBox命令来检查sub是否正确调用并且它正在工作,它是什么.此外,它返回了我所请求的特定位置的值,并且还说明了我正在查看的特定矩阵的大小,因此数据似乎确实被正确读取 – 问题在于随后从新子写入.
当我包含最后一行时,它不会将我的数组打印到工作表中,它也会阻止用户定义的函数正常工作.有谁知道为什么这不起作用?
用户定义的函数可以调用打印到工作表的subs吗?有没有办法来解决这个问题?
最佳答案 总结一下:
当我使用在工作表的单元格中输入的用户定义函数时,我无法将数据导出到除该单元格之外的任何位置.但是,我可以在立即窗口中查看数组.
在MS Excel 2010中,可以在VBA编辑器(Alt F11)中找到立即窗口,然后单击视图 – >立即窗口(Ctrl G).
要将我的数组导出到立即窗口,我应该在我要查看的数组之后将其输入到我的代码中:
Call WriteArrayToImmediateWindow(MyArray)
其中’MyArray’是我的数组的名称,无论是什么.
然后,这将调用’WriteArrayToImmediateWindow’子,即:
Sub WriteArrayToImmediateWindow(arrSubA As Variant)
Dim rowString As String
Dim iSubA As Long
Dim jSubA As Long
rowString = ""
Debug.Print
Debug.Print "The array is: "
For iSubA = 1 To UBound(arrSubA, 1)
rowString = arrSubA(iSubA, 1)
For jSubA = 2 To UBound(arrSubA, 2)
rowString = rowString & "," & arrSubA(iSubA, jSubA)
Next jSubA
Debug.Print rowString
Next iSubA
End Sub
以上信用转到User3706920:How to print two dimensional array in Immediate window in VBA?
编辑:
我决定在立即窗口中查看数组并不总是有用,我需要在Excel中查看以逗号分隔的数据.如果您想这样做,请按照以下说明操作:
要将数组导出到文本文件,您应该在要查看的数组后将其输入到代码中:
Call WriteToFile(MyArray)
其中’MyArray’再次是您要查看的数组的名称. ‘WriteToFile宏如下:
Sub WriteToFile(arrSubA As Variant)
'To export array to a text file
'Setup
Dim FSO As Object
Dim ofs As Object
Dim Output As Variant
Dim rowString As String
Dim iSubA As Long
Dim jSubA As Long
rowString = ""
'Create file
Set FSO = CreateObject("Scripting.FileSystemObject")
Dim oFile As Object
Set oFile = FSO.CreateTextFile("C:\Users\" & Environ$("username") & "\Desktop\Array.txt")
oFile.Close
For iSubA = 1 To UBound(arrSubA, 1)
rowString = arrSubA(iSubA, 1)
For jSubA = 2 To UBound(arrSubA, 2)
rowString = rowString & "," & arrSubA(iSubA, jSubA)
Next jSubA
If Len(Dir("C:\Users\" & Environ$("username") & "\Desktop\Array.txt")) > 0 Then
Set ofs = FSO.OpenTextFile("C:\Users\" & Environ$("username") & "\Desktop\Array.txt", 8, True)
End If
ofs.WriteLine rowString
ofs.Close
Next iSubA
End Sub
要在Excel中快速查看输出数组而不使用任何逗号,我建议将以下宏指定给按钮:
Sub OpenArrayFile()
'To open array text file in Excel
Workbooks.OpenText Filename:="C:\Users\" & Environ$("username") & "\Desktop\Array.txt", Origin:= _
xlMSDOS, StartRow:=1, DataType:=xlDelimited, TextQualifier:=xlDoubleQuote _
, ConsecutiveDelimiter:=False, Tab:=True, Semicolon:=False, Comma:=True _
, Space:=False, Other:=False, FieldInfo:=Array(1, 1), _
TrailingMinusNumbers:=True
End Sub
希望这对其他人也有用!