VBAjoin范围

所以我有一个恒定的7个范围,它们都是一个单元格的宽度和一个大的任意高度,它们之间是相同的。 是否可以join范围,使我有一个范围,只有所有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 

您不能从不同的工作表范围上运行UNION()范围限制在一张纸上的一组单元格中。

编辑#1:

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

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

在这里输入图像说明

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

我通过获取行数范围来解决它:

 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函数find了正确的列字母,我也可以得到正确的使用范围。

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