1

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

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

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

4

2 回答 2

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
于 2012-11-14T16:53:18.900 回答
0

子解析()

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

结束子

于 2014-04-15T08:47:34.180 回答