如何从多个工作表范围引用字符串中捕获单个Excel工作表范围?

时间:2012-11-14 16:19:38

标签: excel vba excel-vba range worksheet

我有一个传递给VBA子的字符串,其格式为“Sheet1:Sheet5!A1:D10”,指的是同一工作簿中多个工作表的范围(Sheet2,Sheet3和Sheet4在Sheet1和Sheet5之间) )。

我遇到的问题是我不能将这个引用应用于范围变量,据我所知,这是由于多个引用,我不能使用application.union,因为范围在不同的工作表上。

如何从此字符串中提取Sheet1的五个单独范围!A1:D10,Sheet2!A1:D10等等?

2 个答案:

答案 0 :(得分:3)

这将获取每个字符串的字符串表示形式,然后存储在数组中。它做了一些假设(表单存在,列出的第一个是索引顺序中的第一个,你希望两者之间关于索引等等),但它可能适用于你的情况:

Sub Parse()

    Dim wbk As Workbook
    ' Arbitrary array size of 10 to store the ranges (as an example)
    Dim myRanges(10) As Variant

    Set wbk = ActiveWorkbook

    ' Split the string at the !
    s = "Sheet1:Sheet3!A1:D10"
    s = Split(s, "!")

    ' Range is the second element of the split (A1:D10)
    TargetRange = s(1)

    ' The first contains the sheets, so split on the :
    SheetNames = Split(s(0), ":")

    ' These sheets are the lower/upper bounds, so use their indices in a loop
    ' that cycles over the sheets in between them (inclusive)
    j = 0 ' This is for the array - you may not need it
    For i = wbk.Sheets(SheetNames(0)).Index To wbk.Sheets(SheetNames(1)).Index
      ' Range is the concatenation of the sheet at this index and the target range
      Set Rng = Range(wbk.Sheets(i).Name & "!" & TargetRange)
      ' Drop it in to our array (or handle how you want)
      myRanges(j) = Rng
      j = j + 1
    Next i

End Sub

答案 1 :(得分:0)

Sub Parse()

Dim wbk As Workbook
' Arbitrary array size of 10 to store the ranges (as an example)
Dim myRanges(10) As Variant

Set wbk = ActiveWorkbook

' Split the string at the !
s = "Sheet1:Sheet3!A1:D10"
s = Split(s, "!")

' Range is the second element of the split (A1:D10)
TargetRange = s(1)

' The first contains the sheets, so split on the :
SheetNames = Split(s(0), ":")

' These sheets are the lower/upper bounds, so use their indices in a loop
' that cycles over the sheets in between them (inclusive)
j = 0 ' This is for the array - you may not need it
For i = wbk.Sheets(SheetNames(0)).Index To wbk.Sheets(SheetNames(1)).Index
  ' Range is the concatenation of the sheet at this index and the target range
  Set Rng = Range(wbk.Sheets(i).Name & "!" & TargetRange)
  ' Drop it in to our array (or handle how you want)
  myRanges(j) = Rng
  j = j + 1
Next i

End Sub