|
老师好,我写了一个自定义的VBA函数,想实现的功能 就是 让用户在单元格中输入这个函数,函数有两个参数,第一个是框选单元格区域,例如:A3:Z6 第二个是输出目标单个单元格的位置, 例如 AF2 单元格
回车完毕后,在AF2单元格 输出数据处理的结果,是一个扩展区域,调试下面代码过程中数据处理没有问题,但是就是无法在AF2单元格输出brr的内容,希望老师帮忙给看看,具体代码如下:
中间数据处理的过程可以忽略,运行没有问题,就是最后输出的时候一直无法正常输出。 关键的是这行代码:wsDest.Range(destCell.Address).Resize(k4, UBound(brr, 2)).Value = brr 一直输不出结果。
Function ProcessData2(sourceRange As Range, destCell As Range) As Variant
Dim wsSource As Worksheet
Dim wsDest As Worksheet
Dim arr As Variant
Dim brr() As Variant
Dim i As Long, j As Long
Dim m As Long
Dim k1 As Long, k2 As Long, k3 As Long, k4 As Long
Dim colCount As Long
Dim stepSize As Long
' 获取源工作表和目标工作表
Set wsSource = sourceRange.Worksheet
Set wsDest = destCell.Worksheet ' 目标工作表应与目标单元格在同一工作表
' 将数据范围的值存入数组 arr
arr = sourceRange.Value
' 重新定义数组 brr
colCount = UBound(arr, 2) ' arr 的列数
ReDim brr(1 To 1000, 1 To 3) ' 假设最多有 1000 行数据
brr(1, 1) = "1个TRUE": brr(1, 2) = "2个TRUE": brr(1, 3) = "3个以上TRUE"
' 确定最后一行
m = UBound(arr, 1)
k1 = 1: k2 = 1: k3 = 1
' 处理数据
stepSize = 3
For i = 1 To colCount - 3 Step stepSize
If arr(m - 1, i + 2) = True And arr(m - 2, i + 2) = True And arr(m - 3, i + 2) = True Then
k3 = k3 + 1
brr(k3, 3) = arr(m, i + 1)
ElseIf arr(m - 1, i + 2) = True And arr(m - 2, i + 2) = True Then
k2 = k2 + 1
brr(k2, 2) = arr(m, i + 1)
ElseIf arr(m - 1, i + 2) = True Then
k1 = k1 + 1
brr(k1, 1) = arr(m, i + 1)
End If
Next i
' 确保 k4 为有效值
k4 = Application.WorksheetFunction.Max(k1, k2, k3)
' 清除目标区域的内容(如果需要的话)
wsDest.Range(destCell.Address).Resize(999, 3).ClearContents
If k4 > 0 Then
wsDest.Range(destCell.Address).Resize(k4, UBound(brr, 2)).Value = brr
ProcessData2 = "true"
Else
wsDest.Range(destCell.Address).Value = "No Data"
ProcessData2 = "false"
End If
' 将结果作为函数返回值
End Function
|
|