选定范围的Excel VBA数组

时间:2016-09-13 12:51:25

标签: excel vba excel-vba

我知道如何在每列上创建两个函数(在本例中为TRIM和STRCONV到ProperCase

Dim arrData() As Variant
Dim arrReturnData() As Variant
Dim rng As Excel.Range
Dim lRows As Long
Dim lCols As Long
Dim i As Long, j As Long

Range("H2", Range("H2").End(xlDown)).Select           
lRows = Selection.Rows.Count
lCols = Selection.Columns.Count

ReDim arrData(1 To lRows, 1 To lCols)
ReDim arrReturnData(1 To lRows, 1 To lCols)

Set rng = Selection
arrData = rng.Value

For j = 1 To lCols
    For i = 1 To lRow
        arrReturnData(i, j) = StrConv(Trim(arrData(i, j)), vbProperCase)
    Next i
Next j

rng.Value = arrReturnData
Set rng = Nothing

目前我正在试图弄清楚如何添加一个FOR,我可以收集多个选择范围,例如:

Set myAnotherArray(0) = Range("H2", Range("H2").End(xlDown)).Select
Set myAnotherArray(1) = Range("J2", Range("J2").End(xlDown)).Select
For k = 1 To myAnotherArray.lenght

因为我正在复制并粘贴整个脚本以在三列上进行调整。已经尝试过:

Dim Rng As Range
Dim Area As Range

Set Rng = Range("Range("H2", Range("H2").End(xlDown)).Select,Range("J2", Range("J2").End(xlDown)).Select")
For Each Area In Rng.Areas
    Area.Font.Bold = True
Next Area

甚至试过联盟范围,但我失败了。任何sugesstions?

一如既往......谢谢你的时间!

1 个答案:

答案 0 :(得分:0)

我找到了一种方法可以用来执行这些范围的工作,请参考下面的代码:

Sub DoSomethingWithRanges()

Dim m_Worksheet      As Excel.Worksheet
Dim m_Columns()      As Variant

Set m_Worksheet = ActiveSheet

' fill all your columns in here
m_Columns = Array(2, 3, 4)

For Each m_Column In m_Columns

   ' the area being used ranges from the second until the last row of your column
   With m_Worksheet.Range(m_Worksheet.Cells(2, m_Column), m_Worksheet.Cells(m_Worksheet.UsedRange.Rows.Count, m_Column))
      ' do things with range
      .Font.Bold = True
   End With
Next m_Column

End Sub

在变体数组m_Columns中,您可以添加所需的所有列。唯一的缺点是,在我的示例中,您必须使用数字来指定列而不是“H”。但是,您不必担心行索引,因为该区域自动从第二行到最后一行使用。