【发布时间】:2018-04-21 09:52:04
【问题描述】:
请看附件了解我的查询的输出(我在图像中提到了标题以供您理解,实际上,输出的标题是空白的)。
我的代码仅在 k 的第一次迭代中运行,然后在下面提到的行中出现错误“下标超出范围。此外,我的删除重复项没有在代码中提供所需的输出。是因为空格或者我该如何解决这两个问题?
我是第一次使用数组。
Dim MoNameArr
Dim arr()
Dim ColLtrg, ColLtrgp, GPLLastCol, GPLLastRow as Long
i = 0
ReDim arr(0)
With wsg
For k = 2 To GPLLastRow
.Cells(k, GPLLastCol + 1).Value = .Cells(k, 2).Value & .Cells(k, 3).Value
If .Cells(k, 4).Value = .Cells(k, 8).Value And .Cells(k, 4).Value = .Cells(k, 9).Value Then
i = k - 2
arr(i) = .Cells(k, 2).Value 'Subscript out of range error
.Cells(k, GPLLastCol + 2).Value = arr(i)
ReDim Preserve arr(i)
End If
Next k
ColLtrg = Replace(.Cells(1, GPLLastCol + 2).Address(True, False), "$1", "")
.Range(ColLtrg & "1:" & ColLtrg & GPLLastRow).RemoveDuplicates Columns:=1, Header:=xlNo
MoNameArr = .Range("AD1:AD" & GetLastRow(wsg, GPLLastCol + 2))
End With
For Each Item In MoNameArr
'Do something
Next Item
Public Function GetLastCol(ByVal ws As Worksheet, rowNum As Long) As Long
With ws
GetLastCol = .Cells(rowNum, Columns.Count).End(xlToLeft).Column
End With
End Function
Public Function GetLastRow(ByVal ws As Worksheet, colNum As Long) As Long
With ws
GetLastRow = .Cells(Rows.Count, colNum).End(xlUp).Row
End With
End Function
【问题讨论】:
-
谁投了反对票,如果您不能提供解决方案,请提供原因。我正在学习 vba,并且第一次遇到数组(无论如何都在做我的第二个作业),我无法通过阅读与数组相关的文章来弄清楚很多东西。
-
只是想注意:这个声明:
Dim ColLtrg, ColLtrgp, GPLLastCol, GPLLastRow as Long只是将GPLLastRow声明为Long。其他默认为Variant。