使用公共variables来存储path,并在另一个模块中使用它

我有一个不同模块的工作簿,每个模块都有不同的目的。

代码的function:一个模块打开一个FileDialog框,要求用户select源文件(.csv)的path,然后search每个源文件的名称并将其粘贴到主工作簿中。

第二个模块读取文件名并使用“pathS”variables; 从第一个模块获取来自源工作簿的信息。

第三个模块清除所有信息并将其输出到新的工作簿。

我已经尝试过了:variablespathS在第一个模块中定义为源文件的位置,然后在模块2中用于定位文件(用于信息提取)。 我在模块1之外宣布它是公开的。

问题:当我运行模块2时,找不到源文件。

问题:我使用variables的方式有什么问题吗?

相关编码:

模块1:

Option Explicit Global pathS As String Sub Counter() Dim count As Integer, i As Long, var As Integer Dim ws As Worksheet Dim w As Workbook Dim Filename As String Dim FileTypeUserForm As UserForm Dim x As String Dim varResult As Variant Dim OutPath As String, OutPathS As String, wPos As Long Set w = ThisWorkbook Application.Calculation = xlCalculationManual 'source input by user varResult = Application.GetSaveAsFilename(FileFilter:="Comma Separated Values Files" & "(*.csv), *.csv", Title:="OutPath", InitialFileName:="D:StartingPath") If varResult <> False Then OutPath = varResult w.Worksheets("FILES").Cells(1, 4) = varResult Else Exit Sub End If wPos = InStr(OutPath, "\StartingPath") OutPathS = Mid(OutPath, 1, wPos - 1) pathS = OutPathS & "\*.*" Filename = Dir(pathS) ThisWorkbook.Sheets("FILES").Range("A:A").ClearContents x = GetValue If x = "EndProcess" Then Exit Sub Set ws = ThisWorkbook.Sheets("FILES") i = 0 Do While Filename <> "" var = InStr(Filename, x) If var <> 0 Then i = i + 1 ws.Cells(i + 1, 1) = Filename Filename = Dir() Else: Filename = Dir() End If Loop Range("A2:A" & i).Sort key1:=Range("A2"), order1:=xlAscending, Header:=xlNo 'this will sort the names directly in the "FILES" sheet Application.Calculation = xlCalculationAutomatic ws.Cells(1, 2) = i MsgBox i & " : files found in folder" End Sub 

模块2(仅限于错误行):

 Sub Gatherer() Dim w As Workbook Dim w2 As Workbook Dim start1 As Long, end1 As Long, end2 As Long, i As Long, lRow As Long, lColumn As Long, t As Long, k As Long, position As Long, g As Long, C As Long Dim WBArray() As Variant Dim Cell As Range Dim ws As Worksheet Dim MyFolder As String Dim MyFile As String Set w = ThisWorkbook 'clean all worksheets in the main file (except FILES), and set date format For Each ws In w.Worksheets If ws.Name <> "FILES" Then ws.UsedRange.ClearContents ws.Range("D1", "XFD1").NumberFormat = "yyyy-mm-dd" End If Next ws 'Optimize Macro Speed Start Application.ScreenUpdating = False Application.EnableEvents = False Application.Calculation = xlCalculationManual 'opens the first workbook file For i = 2 To ThisWorkbook.Sheets("FILES").Cells(1, 2).Value + 1 'has to be +1, otherwise the last source file is not accounted for 'error is in this next line, it does not find the file Workbooks.Open Filename:=pathS & ThisWorkbook.Sheets("FILES").Cells(i, 1).Value 

您可以将模块名称作为variables的前缀,以确保您尝试访问哪个variables,以及您是否有权访问variables。

示例工作正常:

模块1

 Option Explicit Public foo As String Sub Test1() Module1.foo = "bar" Module2.Test2 End Sub 

单词数

 Option Explicit Sub Test2() MsgBox Module1.foo End Sub