0

我是 VBA 新手,我正在尝试访问我用 2 选择的文件,GetOpenFilename问题是我有两个 GetOpenFilename 里面

Private Sub Workbook_Open()
MsgBox "Please select Inventory File"
inventory = Application.GetOpenFilename("Text files(*.xlsx),*.xlsx", , "Please select Inventory File")
Set inventoryWorkbook = Application.Workbooks.Open(inventory)
MsgBox "Please select Material List File"
MaterialList = Application.GetOpenFilename("Text files(*.xlsx),*.xlsx", , "Please select Material List File")
Set materialListWorkbook = Application.Workbooks.Open(MaterialList)
Call Process(inventoryWorkbook, materialListWorkbook)
End Sub

我正在尝试调用将处理两个输入文件的子进程,这个“进程”在一个模块中,起初我有这个:

Call Process 

并修改为 Public Sub Process()

但这引发了运行时错误“424”:需要对象

所以我把它改成了

 Call Process(inventoryWorkbook, materialListWorkbook)

和模块:

Public Sub Process(inventoryWorkbook, materialListWorkbook)
MsgBox "Enters"
Set MaterialList_Main = materialListWorkbook.Worksheets("Sheet2")
Set MainProjectCode = MaterialList_Main.Range("B2").Value
MsgBox MainProjectCode
End Sub

但它抛出运行时错误'13':类型不匹配,我不知道类型不匹配在哪里或如何修复它。我究竟做错了什么?

4

1 回答 1

1

在每个模块(也是 Thisworkbook 模块)的顶部使用 Option Explicit。
这将大大减少类型不匹配的数量。

Option Explicit 

Dim MaterialList As String
Dim materialListWorkbook as Excel.Workbook

MaterialList = Application.GetOpenFilename("Text files(*.xlsx),*.xlsx", , "Please select Material List File")
Set materialListWorkbook = Application.Workbooks.Open(MaterialList)

Call Process(inventoryWorkbook)

这里有一个错误:

Public Sub Process(inventoryWorkbook As Excel.Workbook, materialListWorkbook As Excel.Workbook)
    dim MaterialList_Main as Excel.Worksheet
    dim MainProjectCode as String 

    MsgBox "Enters" 
    Set MaterialList_Main = materialListWorkbook.Worksheets("Sheet2") 
    MainProjectCode = MaterialList_Main.Range("B2").Value 'Error: no Set for value! 
    MsgBox MainProjectCode 
End Sub

Set 关键字仅用于对象,而不是常规变量。

于 2013-10-24T15:11:20.457 回答