我试图将工作簿传递给子程序,而不必再次打开和关闭它。
我试过这个
Dim ExcelApp As New Excel.Application
Dim ws As Object
Public Function cert()
Set ws = ExcelApp.Workbooks.Open(FileDir).Sheets(1)
If CheckForMutipleUIC(ws) = True Then <---- this is where I call the Function
....
该功能将打开此
Public Function CheckForMutipleUIC(ByVal ws As Excel.Workbook) As Boolean
' Dim ExcelApp As New Excel.Application
' DataFleet = CurrentProject.Path & "\Extract\Fleet.xls"
' Set ws1 = ExcelApp.Workbooks.Open(DataFleet).Sheets(1)
UICCheck = ws.Range("GD2").Value
For Each Cell In ws.Range("GD2:GD10000").cells
If Cell.Text <> "" Then
If Cell.Value <> UICCheck Then
Err.Raise 513, "VICILauncher-DataValidation-CheckForMultipleUIC", "Multiple UICS Found in extract. Please Make sure the correct UIC is being Extracted"
End If
End If
Next
CheckForMutipleUIC = True
Exit Function
但我想我没有正确传递Excel对象。应用程序对象如何在没有关闭和重新打开的情况下传递给sub。
答案 0 :(得分:1)
您尚未包含可能获得的错误消息。但只是查看发布的代码,看起来你将工作表'ws'传递给了期待工作簿的CheckForMutipleUIC函数。尝试更改以下内容。
Public Function CheckForMutipleUIC(ByVal ws As Excel.Workbook) As Boolean
到
Public Function CheckForMutipleUIC(ByVal ws As Excel.Worksheet) As Boolean
答案 1 :(得分:1)
尝试下面的代码,代码注释中的解释:
Option Explicit
Dim ExcelApp As New Excel.Application
Dim wb As Workbook
Dim ws As Worksheet
Dim FileDir As String
'======================================================================
Public Function cert() '<-- NOT SURE why this is a Function and not a Sub ?
' set the workbook object
Set wb = ExcelApp.Workbooks.Open(FileDir)
Set wb = Workbooks.Open(FileDir) ' <-- why not use this if this is inside Excel VBA ?
' set the worksheet object
Set ws = wb.Sheets(1)
If CheckForMutipleUIC(ws) = True Then ' pass the worksheet object to the Function
'....
End If
End Function
'======================================================================
Public Function CheckForMutipleUIC(ByVal ws As Worksheet) As Boolean
Dim Cell As Range
Dim UICCheck
UICCheck = ws.Range("GD2").Value
For Each Cell In ws.Range("GD2:GD10000").Cells
' If Cell.Text <> "" Then
If Cell.Value2 <> "" Then ' <-- use Value 2 instead of Text
If Cell.Value <> UICCheck Then
Err.Raise 513, "VICILauncher-DataValidation-CheckForMultipleUIC", "Multiple UICS Found in extract. Please Make sure the correct UIC is being Extracted"
End If
End If
Next
CheckForMutipleUIC = True
End Function
答案 2 :(得分:1)
您可能必须使用 ByRef (以及已经提到的正确声明):
Public Function CheckForMutipleUIC(ByRef ws As Excel.Worksheet) As Boolean