将工作表作为参数传递给子例程

时间:2015-11-24 16:20:16

标签: excel vba excel-vba

我知道有很多关于这个主题的问题但是我还在努力解决超出范围的下标?是的,我导入的工作簿确实有一张名为LSL Recon的表格,我已经验证了。我已调试并用LSL Recon替换Import Sheets(1)(如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: Calling a sub on another worksheet with multiple arguments
pass sheet to a function (excel vba)
Passing a Worksheet to a subroutine

1 个答案:

答案 0 :(得分:2)

删除公共范围变量,声明所有变量,并根据需要传递参数:

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的结果返回到主过程,则将其更改为Function,并返回一个集合对象,并调用它:

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

然后功能:

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