如何从多个工作表范围引用string捕获单个Excel工作表范围?

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

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

如何从这个string中提取Sheet1!A1:D10,Sheet2!A1:D10等五个单独的范围?

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

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 

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 

结束小组