VBA加入范围

时间:2015-05-21 13:22:03

标签: excel vba excel-vba excel-2010

所以我有一个恒定的7个范围,这些范围都是一个单元格宽,并且它们之间的任意高度都是相同的。是否可以加入范围,以便我有一个范围只包含所有7个范围?我已经尝试了UnionRange函数,但它返回的数字远大于预期。

这是我到目前为止所做的:

' acquire the range of each column, using its coumn number and the user-defined Col_Letter function
    Dim rng1 As Range
    Set rng1 = Sheets("sheet_name").Range(Col_Letter(col_1) & ":" & Col_Letter(col_1) & LRow)
    Dim rng2 As Range
    Set rng2 = Sheets("sheet_name").Range(Col_Letter(col_2) & ":" & Col_Letter(col_2) & LRow)
    Dim rng3 As Range
    Set rng3 = Sheets("sheet_name").Range(Col_Letter(col_3) & ":" & Col_Letter(col_3) & LRow)
    Dim rng4 As Range
    Set rng4 = Sheets("sheet_name").Range(Col_Letter(col_4) & ":" & Col_Letter(col_4) & LRow)
    Dim rng5 As Range
    Set rng5 = Sheets("sheet_name").Range(Col_Letter(col_5) & ":" & Col_Letter(col_5) & LRow)
    Dim rng6 As Range
    Set rng6 = Sheets("sheet_name").Range(Col_Letter(col_6) & ":" & Col_Letter(col_6) & LRow)
    Dim rng7 As Range
    Set rng7 = Sheets("sheet_name").Range(Col_Letter(col_7) & ":" & Col_Letter(col_7) & LRow)

    ' Join the ranges of each column into one range
    Dim UnionRange As Range
    Set UnionRange = Union(rng1, rng2, rng3, rng4, rng5, rng6, rng7)
    Debug.Print "Width of UnionRange: " & UnionRange.width
    Debug.Print "Height of UnionRange: " & UnionRange.height

3 个答案:

答案 0 :(得分:3)

您无法在不同工作表的范围内运行 UNION()范围仅限于单张纸上的一组单元格。

修改#1:

我怀疑你的Debug.Print。您正在打印像素相关变量而不是行数

Sub dural()
   Dim r As Range
   Set r = Range("A1:C5")
   MsgBox r.Height & vbCrLf & r.Rows.Count
End Sub

enter image description here

答案 1 :(得分:1)

尝试使用unionrange.rows.count和unionrange.columns.count,而宽度和高度可能会使用边框单元格地址之间的差异而不是计算它

答案 2 :(得分:0)

我通过获取行号边界来解决它:

Dim FirstRow As Long, LastRow As Long    
With Get_Workbook.Sheets("Sheet_Name").UsedRange
     FirstRow = .Row
     LastRow = .Rows(UBound(.Value)).Row
End With

从那里,我将我的代码修改为这种格式:

Dim rng1 As Range
Set rng1 = Get_Workbook.Sheets("Sheet_Name").Range(Col_Letter(col_1) & FirstRow & ":" & Col_Letter(col_1) & LastRow)

这样,我已经使用Col_Letter函数找到了正确的列字母,我也可以获得正确的使用范围。

请注意,Get_Workbook和Col_Letter是用户定义的函数。