比方說,我們有以下陣列:VBA的Excel:單元陣列,包括合併單元格值
的第二和第三小區合併在一起。 如何讓數組讀取第二個值而不是空值?
當前代碼:
Sub arrayTest() Dim rng As Range Set rng = Range(Cells(1, 1), Cells(4, 1)) Debug.Print rng(1) & "," & rng(2) & "," & rng(3) & "," & rng(4) End Sub
輸出:1,2,,4
比方說,我們有以下陣列:VBA的Excel:單元陣列,包括合併單元格值
的第二和第三小區合併在一起。 如何讓數組讀取第二個值而不是空值?
當前代碼:
Sub arrayTest() Dim rng As Range Set rng = Range(Cells(1, 1), Cells(4, 1)) Debug.Print rng(1) & "," & rng(2) & "," & rng(3) & "," & rng(4) End Sub
輸出:1,2,,4
我已經解決了這個問題我自己。這適用於我怎麼想它的工作:
Sub arrayTest2() Dim LastRow As Long With Worksheets(1) LastRow = .Cells(.Rows.Count, 1).End(xlUp).Row End With Dim rng As Range Set rng = Range("A1:A" & LastRow) Dim cellA As Range Dim arrayA() As Variant ReDim arrayA(LastRow)
For Each cellA In rng arrayA(cellA.Row) = cellA.MergeArea(Cells(1, 1).Value) Debug.Print arrayA(cellA.Row) Next cellA End Sub
你可以使用一個循環排除打印空白單元格
Dim i As Integer
Sub arrayTest()
Dim rng As Range
Set rng = Range(Cells(1, 1), Cells(4, 2))
For i = 0 To 4
If Not IsEmpty(rng(i)) Then
Debug.Print rng(i)
End If
Next
End Sub
在的地方,我不認爲這將有可能讓Excel按照你想要的方式閱讀(除非你像Matt已經演示的那樣使用循環在內存中構建數組)。如果我理解正確,那麼你想輸出像1,2,2,4。
示例代碼使用臨時空列得到這樣的結果:
Sub ArrayTest2()
Const tmpCol As Long = 2 '\\ Change this to suit. This will be your temporary column
Dim rngIn As Range, rngOut As Range
Set rngIn = Range(Cells(1, 1), Cells(4, 1))
rngIn.Copy Cells(1, tmpCol)
Set rngOut = Cells(1, tmpCol).Resize(rngIn.Count, 1)
With rngOut
.UnMerge
If .SpecialCells(xlCellTypeBlanks).Count > 0 Then .SpecialCells(xlCellTypeBlanks).FormulaR1C1 = "=R[-1]C"
.Value = .Value
End With
Debug.Print rngOut(1) & "," & rngOut(2) & "," & rngOut(3) & "," & rngOut(4)
Cells(1, tmpCol).EntireColumn.Delete
End Sub
'範圍(3,1).MergeArea.Cells(1,1).Value'工程獲得的價值,但我想在陣列把它撿起來自動 – SLT
所以你想要第二個值是空白的,或三個值要返回?你如何使用這個輸出? – SJR
我想用列中的值創建一個數組,而不是爲每個單元格指定是否合併。 debug.Print只是表明它是否成功完成(調試目的) – SLT