在VBA中更改数组
我想将值交换成multidimensional array,不是#N / A或不是0的每行。 所以input表是在一个电子表格中包含下面的数字,问题是我不能交换他们如何我想要的。
24 20 0 #N/A #N/A #N/A 21 20 0 #NA #N/A #N/A 25 24 20 0 #N/A #N/A 26 25 24 20 0 #N/A 28 26 25 24 20 0
你有什么build议如何处理?
Sub FlipRows() Dim Rng As Range Dim WorkRng As Range Dim arr As Variant Dim i As Integer, j As Integer, k As Integer Dim matrix As Range, matrix2 As Range Set matrix = Range("A1:F5") Set matrix2 = Range("A7:F11") 'Set tempMatrix as String, tempMatrix2 as String On Error Resume Next 'matrix.Select 'matrix.Copy 'matrix2.Select 'matrix2.PasteSpecial Set WorkRng = Application.Selection arr = WorkRng.Formula For i = 1 To UBound(arr, 1) k = UBound(arr, 2) For j = 1 To UBound(arr, 2) / 2 xTemp = arr(i, j) arr(i, j) = arr(i, k) arr(i, k) = xTemp k = k - 1 Next Next WorkRng.Formula = arr End Sub
假设你无效的值(0和#NA
)总是在每一行的右边,这应该是:
For i = LBound(arr, 1) To UBound(arr, 1) 'first search backward the first valid entry For k = UBound(arr, 2) To LBound(arr, 2) Step -1 If Not IsError(arr(i, k)) Then If arr(i, k) <> 0 And arr(i, k) <> "#NA" Then Exit For Next 'Now do the swap in the valid region For j = LBound(arr, 2) To Int(k / 2) Dim temp: temp = arr(i, j) arr(i, j) = arr(i, LBound(arr, 2) + k - j) arr(i, LBound(arr, 2) + k - j) = temp Next Next WorkRng.Formula = arr
假设你想要交换的值之后总是有一个零值
Sub swap() Set r = Range("A1:F5") For Each ro In r.Rows Set re = ro.Find(0, lookat:=xlWhole) co = re.Column For c = 1 To (co - 1) / 2 a = ro.Cells(1, c) ro.Cells(1, c) = ro.Cells(1, co - c) ro.Cells(1, co - c) = a Next c Next ro
结束小组