Excel VBA 将范围设置为多列
Excel VBA set range as multiple columns
我目前正在尝试将多个列分配给一个范围。我需要使用工作表名称和列号来引用列。
dim MyRange as Range
dim StartCol as Integer
set MyRange = [from column StartCol until Startcol+5]
任何输入将不胜感激...
Option Explicit
Sub col()
Dim rngCols As Range, ws As Worksheet, wb As Workbook
Dim startCol As Integer
set wb = ThisWorkbook
set ws = wb.Sheets("MySheet")
startCol = 1
With ws
Set rngCols = .Range(.Cells(1, startCol), .Cells(.Rows.Count, startCol + 5))
End With
rngCols.Select
End Sub
这应该可以满足您的需求。您只需要修改 startCol 变量、工作表变量和要添加到 startCol 的整数。
'
' get the columns of range Rr
' Cols as CSV like 2,4,7 b,d,G B,D:F,m,P 3,H,J,2
' 3,4,5,6 is C:F 6,8:11,3 is bad => 6,8,3 B,D:F is 2,4,5,6
'
Function GetRaColl(Rr As Range, ColS$) As Range
Dim SA$(), LI&, VV&, UB&, URa As Range
SA = Split(ColS, ",")
UB = UBound(SA)
VV = Val(SA(0))
If VV > 0 Then
Set URa = Rr.Columns(VV)
Else
Set URa = Rr.Columns(SA(LI))
End If
' if more ranges
For LI = 1 To UBound(SA)
VV = Val(SA(LI))
If VV > 0 Then ' so treats 3:5 as 3 so use C:E or 3,4,5
Set URa = Union(URa, Rr.Columns(VV))
Else
Set URa = Union(URa, Rr.Columns(SA(LI)))
End If
Next LI
Set GetRaColl = URa
End Function
我目前正在尝试将多个列分配给一个范围。我需要使用工作表名称和列号来引用列。
dim MyRange as Range
dim StartCol as Integer
set MyRange = [from column StartCol until Startcol+5]
任何输入将不胜感激...
Option Explicit
Sub col()
Dim rngCols As Range, ws As Worksheet, wb As Workbook
Dim startCol As Integer
set wb = ThisWorkbook
set ws = wb.Sheets("MySheet")
startCol = 1
With ws
Set rngCols = .Range(.Cells(1, startCol), .Cells(.Rows.Count, startCol + 5))
End With
rngCols.Select
End Sub
这应该可以满足您的需求。您只需要修改 startCol 变量、工作表变量和要添加到 startCol 的整数。
'
' get the columns of range Rr
' Cols as CSV like 2,4,7 b,d,G B,D:F,m,P 3,H,J,2
' 3,4,5,6 is C:F 6,8:11,3 is bad => 6,8,3 B,D:F is 2,4,5,6
'
Function GetRaColl(Rr As Range, ColS$) As Range
Dim SA$(), LI&, VV&, UB&, URa As Range
SA = Split(ColS, ",")
UB = UBound(SA)
VV = Val(SA(0))
If VV > 0 Then
Set URa = Rr.Columns(VV)
Else
Set URa = Rr.Columns(SA(LI))
End If
' if more ranges
For LI = 1 To UBound(SA)
VV = Val(SA(LI))
If VV > 0 Then ' so treats 3:5 as 3 so use C:E or 3,4,5
Set URa = Union(URa, Rr.Columns(VV))
Else
Set URa = Union(URa, Rr.Columns(SA(LI)))
End If
Next LI
Set GetRaColl = URa
End Function