簡體   English   中英

VBA Excel:單元格數組,包括合並的單元格值

[英]VBA Excel: Array of cells including merged cell values

假設我們有以下數組:

Excel數組

第二和第三單元格合並在一起。 我如何使數組將第三個值讀取為2而不是空值?

當前代碼:
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

您可以使用循環將空白單元格從打印中排除

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

我已經解決了這個問題。 這適用於我希望它如何工作:
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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM