将工作表作为parameter passing给子例程

我知道在这个话题上有很多问题,但是我还在挣扎着超出范围的下标吗? 是的,我正在导入的工作簿中有一张标题为LSL Recon的表单,我已经validation过了。 我已经debugging并用Import Sheets(1)replaceLSL Recon (如Sheet1 ),然后该过程会继续进一步,但不会导入任何内容到数组中。

 Option Explicit Public FILENAME, c_DATE, cNAME As String 'Public ws As Worksheet Sub main() Application.DisplayAlerts = True Application.ScreenUpdating = False CLEAR Import Sheets("LSL Recon") Display_Import End Sub() Sub Import(ws As Worksheet) Workbooks.Open FILENAME Set TempBook = ActiveWorkbook ws.Activate cNAME = "Entity" cA = Sheets(1).Rows.Find(What:=UCase(cNAME), LookAt:=xlWhole, SearchDirection:=xlNext).Column cNAME = "Sector" cB = Sheets(1).Rows.Find(What:=UCase(cNAME), LookAt:=xlWhole, SearchDirection:=xlNext).Column cNAME = "Date" cC = Sheets(1).Rows.Find(What:=UCase(cNAME), LookAt:=xlWhole, SearchDirection:=xlNext).Column cNAME = "Client" cD = Sheets(1).Rows.Find(What:=UCase(cNAME), LookAt:=xlWhole, SearchDirection:=xlNext).Column ... End Sub() 

有用的问题:
VBA:使用多个参数调用另一个工作表上的子项
传递表函数(excel vba)
将工作表传递给子例程

摆脱你的公共范围variables,声明所有variables,并根据需要传递参数:

 Option Explicit Sub main() Dim FILENAME$ Dim c_DATE$ Dim cNAME$ Dim wsName$ wsName = "LSL Recon" Application.DisplayAlerts = True Application.ScreenUpdating = False CLEAR Import (wsName) Display_Import End Sub Sub Import(wsName$) Dim wb as Workbook Dim cNames, itm, found ' Use an array of items to search for cNames = Split("Entity,Sector,Date,Client",",") Set wb = Workbooks.Open(FILENAME) Set ws = wb.Sheets(wsName) For Each itm in cNames found = ws.Rows.Find(What:=UCase(cNAME), LookAt:=xlWhole, SearchDirection:=xlNext).Column Debug.Print cName " found in column: " & found Next End Sub 

如果您需要将.Find的结果返回到主过程,那么将其更改为一个函数,并返回一个集合对象,并像这样调用它:

 Set foundItems = Import(wsName) Dim itm For each itm in foundItems Debug.Print itm Next 

那么function:

 Function Import(wsName$) Dim wb as Workbook Dim ret as New Collection Dim cNames, itm, found ' Use an array of items to search for cNames = Split("Entity,Sector,Date,Client",",") Set wb = Workbooks.Open(FILENAME) Set ws = wb.Sheets(wsName) For Each itm in cNames ret.Add ws.Rows.Find(What:=UCase(cNAME), LookAt:=xlWhole, SearchDirection:=xlNext).Column Debug.Print cName " found in column: " & ret(ret.Count) Next 'return the collection to the calling procedure Set Import = ret End Function