2016-08-26 7 views
0

この問題は、最初のサブブックでワークブックをインポートして開きますが、2番目のサブブランドでワークブックを参照していますが、今は静的な名前です(私はいくつかの一重引用符で線を示しています)。別のサブ(VBA)で見つけたワークブックファイルのパスを参照する

私は変数 "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 

答えて

1

通常は2番目のサブ引数としてワークブックを渡します

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 

編集:私はあなたが実際にOneからTwoを呼び出すことはありません気付いので、代替(ではないとして堅牢)方法は:

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 
関連する問題