|
本帖最后由 microyip 于 2018-12-25 08:30 编辑
很经常发生使用系统数组转置函数Application.WorksheetFunction.Transpose时出错的情况,目前个人碰到的原因无非就是两种:1、数组元素超过65536和某元素长度超过255字符
2、SQL读取得到的数据里存在Null数值或者读取表里的数值存在错误值
为此,个人就建立了一个自定义转置函数,以便转换。又加上最近有朋友在论坛里咨询转置出错的解决方案,特此分享。如有不当之处,敬请高手指正。2018.12.25,更新代码,增加了转置结果形式
- Function TranVariant(ByVal vData As Variant, Optional ByVal bNoDimension2 As Boolean = False) As Variant
- '对二维以下进行转置数组
- '参数说明:
- ' bNoDimension,vData(2 To 3, 4 To 4)转置后是否转为vData(1 To 2)形式或vData(2 To 2, 3 To 4)转置后是否转为vData(1 To 2)形式
- '返回值说明:
- ' 错误信息:数组维数大于2
- ' 原vData值:非数组
- ' 数组:已经按要求转置的数组
- Dim nDimension As Integer '维度
- Dim vNewData As Variant, nRow As Double, nCol As Double
-
- nDimension = -1
- If IsArray(vData) Then
- On Error Resume Next
- Do While Err.Number = 0
- nDimension = nDimension + 1
- If nDimension = 0 Then
- vNewData = vData(LBound(vData)) '检查是否vData(1)形式数组
- If Err.Number = 0 Then Exit Do
- Else
- vNewData = UBound(vData, nDimension + 1)
- End If
- Loop
- Err.Clear
- On Error GoTo 0
-
- If nDimension > 2 Then
- vNewData = "数组维数大于2!"
- ElseIf nDimension = 0 Then
- ReDim vNewData(1 To 1, 1 To UBound(vData) - LBound(vData) + 1)
- For nCol = 1 To UBound(vNewData, 2)
- If Not IsNull(vData(nCol + LBound(vData) - 1)) Then _
- vNewData(1, nCol) = vData(nCol + LBound(vData) - 1)
- Next
- ElseIf bNoDimension2 And (UBound(vData) = LBound(vData) Or UBound(vData, 2) = LBound(vData, 2)) Then
- If UBound(vData) = LBound(vData) Then
- ReDim vNewData(1 To UBound(vData, 2) - LBound(vData, 2) + 1)
- For nCol = 1 To UBound(vNewData)
- If Not IsNull(vData(LBound(vData), nCol + LBound(vData, 2) - 1)) Then _
- vNewData(nCol) = vData(LBound(vData), nCol + LBound(vData, 2) - 1)
- Next
- Else
- ReDim vNewData(1 To UBound(vData) - LBound(vData) + 1)
- For nRow = 1 To UBound(vNewData)
- If Not IsNull(vData(nRow + LBound(vData) - 1, LBound(vData, 2))) Then _
- vNewData(nRow) = vData(nRow + LBound(vData) - 1, LBound(vData, 2))
- Next
- End If
- Else
- ReDim vNewData(1 To UBound(vData, 2) - LBound(vData, 2) + 1, 1 To UBound(vData) - LBound(vData) + 1)
- For nRow = 1 To UBound(vNewData)
- For nCol = 1 To UBound(vNewData, 2)
- If Not IsNull(vData(nCol + LBound(vData) - 1, nRow + LBound(vData, 2) - 1)) Then _
- vNewData(nRow, nCol) = vData(nCol + LBound(vData) - 1, nRow + LBound(vData, 2) - 1)
- Next
- Next
- End If
-
- vData = vNewData
- End If
- TranVariant = vData
- End Function
复制代码
|
评分
-
3
查看全部评分
-
|