我遇到了这个问题,我在第一个子目录中导入并打开一个工作簿,但想在第二个子句中引用它,但我不确定如何。现在它是一个静态名称(我用几个单引号表示该行)。
我尝试引用我的变量" filename"但是因为它必须是工作簿中的表格,所以我不能肯定如何做到这一点。提前谢谢!
Sub Procedure1()
Dim Filt As String
Dim filterindex As Integer
Dim title As String
Dim filename As Variant
Filt = "Comma Seperated Files (*.csv),*.csv"
filterindex = 1
title = "Select a File to Import"
filename = Application.GetOpenFilename _
(FileFilter:=Filt, _
filterindex:=filterindex, _
title:=title)
If filename = False Then
MsgBox "No file was selected"
Exit Sub
End If
Workbooks.Open filename
End Sub
Sub Procedure2()
Dim CurrentWS As Worksheet
Set CurrentWS = ActiveSheet
Dim SourceWS As Worksheet
Set SourceWS = Workbooks("cedar.csv").Worksheets(1)''''''''''''''''''''''
Dim SourceHeaderRow As Integer: SourceHeaderRow = 1
Dim SourceCell As Range
Dim TargetWS As Worksheet
Set TargetWS = Workbooks("Prototype.xlsm").Worksheets(1)
Dim TargetHeader As Range
Set TargetHeader = TargetWS.Range("A1:AX1")
Dim RealLastRow As Long
Dim SourceCol As Integer
SourceWS.Activate
For Each Cell In TargetHeader
If Cell.Value <> "" Then
Set SourceCell = Rows(SourceHeaderRow).Find _
(Cell.Value, LookIn:=xlValues, LookAt:=xlWhole)
If Not SourceCell Is Nothing Then
SourceCol = SourceCell.Column
RealLastRow = Columns(SourceCol).Find("*", LookIn:=xlValues, _
SearchOrder:=xlByRows, SearchDirection:=xlPrevious).Row
If RealLastRow > SourceHeaderRow Then
Range(Cells(SourceHeaderRow + 1, SourceCol), Cells(RealLastRow, _
SourceCol)).Copy
TargetWS.Cells(2, Cell.Column).PasteSpecial xlPasteValues
End If
End If
End If
Next
CurrentWS.Activate
Workbooks("Prototype.xlsm").Sheets(1).Range("A1").Select
End Sub
答案 0 :(得分:2)
通常,您将工作簿作为参数传递给第二个Sub:
Sub One()
Dim wb As Workbook
Set wb = Workbooks.Open(somePath)
Two wb
End sub
Sub Two(wb As Workbook)
With wb.sheets(1)
'work with sheet
End with
End sub
编辑:我发现你实际上并没有从Two
拨打One
,所以另一种选择(但不是那么强健)可能是:
Dim wb As Workbook 'Global variable
Sub One()
Set wb = Workbooks.Open(somePath)
End sub
Sub Two()
With wb.sheets(1) 'use the global variable
'work with sheet
End with
End sub