简体   繁体   English

如何将变量从一个子传递到另一个?

[英]how to pass a variable from one sub to another?

I am struggling to pass a srcFile variable from one sub to another. 我正在努力将srcFile变量从一个子传递到另一个。 I would like to do the following: 我要执行以下操作:

1) load source file from my local path in loadFile() sub 1)从本地路径在loadFile()子目录中加载源文件

2) Set srcFile as my source data workbook 2)将srcFile设置为我的源数据工作簿

3) I would like to call processWorkbook in my Main program so that it will take my srcFile, pass it to the Sub and do some actions on each worksheet of that file. 3)我想在主程序中调用processWorkbook,这样它将获取我的srcFile,将其传递给Sub,然后对该文件的每个工作表执行一些操作。

Apologies if I did not express myself clearly. 抱歉,如果我没有清楚表达自己的意思。

Sub Main()
  Call loadFile
  Call processWorkbook(srcFile)    
End Sub

' _____________________________________________________

Sub loadFile()
  Dim wrk As Worksheet
  Dim trg As Worksheet
  Dim Path As String
  Dim srcFile As Workbook

  Set wrk = Workbooks("Banks.xlsm").Sheets("Control")
  Set trg = Workbooks("Banks.xlsm").Sheets("Output")
  trg.Cells.ClearContents
  Path = wrk.Cells(1, 2).Value 'file path
  Set srcFile = Workbooks.Open(Path, ReadOnly:=False)
End Sub

' _____________________________________________________

Sub processWorkbook(wrk)
  Dim sht As Worksheet

  For Each sht In wrk.Sheets
    Call anotherSub
  Next sht
End Sub

The simplest way to do this is to declare a Workbook object in Sub Main and populate it from loadFile . 最简单的方法是在Sub Main声明一个Workbook对象,并从loadFile填充它。 There would be two ways this could be done: 1) Pass the Workbook object to loadFile by reference, or 2) Set the object from loadFile as an object. 有两种方法可以完成此操作:1)通过引用将Workbook对象传递给loadFile,或2)将loadFile中的对象设置为对象。

I believe the second will be easier for you to understand, so I've used that to modify your code, as below. 我相信第二个将使您更容易理解,因此,我已使用它来修改您的代码,如下所示。

Note that for this to work it was necessary to change loadFile to be a function, rather than a sub. 请注意,要使其正常工作,必须将loadFile为函数而不是子函数。 (A function returns something.) Also, I removed the Call keyword from your code as this is no longer needed / used. (一个函数返回一些信息。)而且,由于不再需要/不再使用它,我从代码中删除了Call关键字。

Sub Main()
   Dim srcFile As Workbook

   Set srcFile = loadFile
   processWorkbook srcFile 

End Sub

'_____________________________________________________

Function loadFile() as Workbook

  Dim wrk As Worksheet
  Dim trg As Worksheet
  Dim Path As String
  Dim srcFile As Workbook

  Set wrk = Workbooks("Banks.xlsm").Sheets("Control")
  Set trg = Workbooks("Banks.xlsm").Sheets("Output")
  trg.Cells.ClearContents
  Path = wrk.Cells(1, 2).Value 'file path
  Set srcFile = Workbooks.Open(Path, ReadOnly:=False)

  Set loadFile = srcFile
End Function

'_____________________________________________________

Sub processWorkbook(wrk)

Dim sht As Worksheet

For Each sht In wrk.Sheets
    Call anotherSub
Next sht

End Sub

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM