在Excel VBA中的Range函数中传递一个variables并对其进行循环

我有一个叫做Shipper VP的源Excel工作表。 发货人VP的单元格B4,C4,D4中有三个人的名字和列中的相应数据。 我为每个人提取数据,并为每个人创build单独的Excel选项卡,并将其重命名为各自的名称。 另外还有一堆其他的计算。 这是代码:(一切正常)

Sub Test() Dim wsSource As Worksheet, ws As Worksheet Dim rg As Range, c As Range Dim n As Integer Set wsSource = Sheets("Shipper VP") Set rg = wsSource.Range("B4:D4") n = 1 For Each c In rg 'add sheet and rename Set ws = Sheets.Add ws.Name = c.Text 'other calculations '... n = n + 1 Next c End Sub 

但是,目前我知道源表(ws.Source)中有三个人,我想循环“n”个人的相同的东西。 对于每个人,从B4开始,继续到C4,D4,E4等,直到源表中的人数。 最后一列是Grand Total,但是我只提取数据直到前一列,而不是Grand Total列。

现在在上面的代码rg范围内,而不是(“B4:D4”),我想D4单元格是一个variables,以便它可以是任何东西像Z4或AK4等。它有三个人,单元格地址从源表(wsSource)是从B4:D4,如果有10个人,它将从B4:K4。 如果再有100个人,则会变成B4:x4,其中x将是源excel表(wsSource)的第(100 + 1)列。

我无法将此variables传递给以下代码:Set rg = wsSource.Range(“B4:D4”)

那么,如果源表中有“n”个人(我可能不知道人数)应该做什么,应该有一个variables,直到从B4开始的单元格值为空,然后在下一个代码它应该自动设置rg = wsSource.Range(“B4:x4”)的范围,其中x是第(100 + 1)列。

但是,在search时,有三个人,它会得到F4列中的空值,而不是在源表单(发货人VP)的E4列中,因为人员的名字是从B4到D4,那么还有一个额外的E4中的总计专栏。 但在rg的范围内,我只想从B4到D4,而不是到E4列。 源表单中的“n”个人也要做同样的事情。

如果B4也是一个variables,那么就好比'y'或者什么的。 然后我可以将'y'设置为B4作为起始单元格号码。 之后,它将从B4循环到源表单(ws.Source)中第4行的倒数第二列值,因为第4行的最后一列值将是总计。

如果有人能帮助我,我会很感激。

谢谢。 问候,Dip

您可以修改您的代码以使用基于单元格编号的范围而不是其字母引用,并使用以下代码抓取正在使用的最后一列。

 Sub Test() Dim first As Long Dim last As Long Dim row As Long Dim wsSource As Worksheet, ws As Worksheet Dim rg As Range, c As Range Dim n As Integer Set wsSource = Sheets("Shipper VP") first = 2 row = 4 With wsSource ' This returns the last column with data. There could be empty cells along the way. 'You could look into converting the column reference into the letter so that you could use a string in the range such as "B4:E4" last = .Cells(row, .Columns.Count).End(-4159).Column - 1 'xlToLeft End With Set rg = wsSource.Range(Cells(row, first), Cells(row, last)) n = 1 For Each c In rg 'add sheet and rename Set ws = Sheets.Add ws.Name = c.Text 'other calculations '... n = n + 1 Next c End Sub