📜  excel vba 连接范围 - VBA (1)

📅  最后修改于: 2023-12-03 14:41:02.971000             🧑  作者: Mango

Excel VBA 连接范围 - VBA

在 Excel VBA 中,连接范围是常见的操作之一。本文将介绍如何使用 VBA 连接 Excel 中的范围。

连接多个范围

要连接多个范围,使用以下语法:

Set combinedRange = Union(range1, range2, ...)

示例代码:

Sub combineRanges()
    Dim range1 As Range
    Dim range2 As Range
    Dim combinedRange As Range
    
    Set range1 = Range("A1:B5")
    Set range2 = Range("C1:D5")
    
    Set combinedRange = Union(range1, range2)
    
    MsgBox combinedRange.Address
End Sub
连接同一行/列的多个范围

要连接同一行/列的多个范围,使用以下语法:

Set combinedRange = range1.Resize(1).Offset(1).Resize(1).Union(range2.Resize(1).Offset(1).Resize(1), ...)

示例代码:

Sub combineRangeByRow()
    Dim range1 As Range
    Dim range2 As Range
    Dim combinedRange As Range
    
    Set range1 = Range("A1:C1")
    Set range2 = Range("E1:G1")
    
    Set combinedRange = range1.Resize(1).Offset(1).Resize(1).Union(range2.Resize(1).Offset(1).Resize(1))
    
    MsgBox combinedRange.Address
End Sub
Sub combineRangeByColumn()
    Dim range1 As Range
    Dim range2 As Range
    Dim combinedRange As Range
    
    Set range1 = Range("A1:A5")
    Set range2 = Range("A7:A10")
    
    Set combinedRange = range1.Resize(1).Offset(1).Resize(1).Union(range2.Resize(1).Offset(6).Resize(1))
    
    MsgBox combinedRange.Address
End Sub
连接多个范围并设置格式

要连接多个范围并设置格式,使用以下语法:

Set combinedRange = Union(range1, range2, ...)
combinedRange.Interior.Color = RGB(255, 255, 0)

示例代码:

Sub combineRangesWithFormat()
    Dim range1 As Range
    Dim range2 As Range
    Dim combinedRange As Range
    
    Set range1 = Range("A1:B5")
    Set range2 = Range("C1:D5")
    
    Set combinedRange = Union(range1, range2)
    combinedRange.Interior.Color = RGB(255, 255, 0)
End Sub

以上就是本文介绍的连接范围的方法。