将路径文件分配到VBA中的变量中

时间:2014-06-16 17:21:24

标签: excel-vba vba excel

我差不多完成了我程序的这一小部分。我试图将路径文件分配给变量,所以我可以在第二部分中使用该变量,我尝试了以下内容。我感谢任何帮助。非常感谢高级

第一部分

 Public strPathAndFile As String  

 Sub CommandButton2_Click()

 Dim fd As FileDialog
 Dim strShortName As String
 Dim strInitialDir As String
 Dim wb As Workbook

 strInitialDir = CurDir   'Save current directory if required

 Set fd = Application.FileDialog(msoFileDialogFilePicker)

 With fd
     .InitialFileName = CurDir & "\"     'Startup folder (Optional line of code)
     .AllowMultiSelect = False
     .Filters.Clear
     .Filters.Add "All Excel Files", "*.xls;*.xlsm;*.xlsx"     'Display excel files only
     If .Show = False Then
         MsgBox "User cancelled without selecting. Processing terminated."
         ChDir (strInitialDir)  'Change back to Initial directory if user cancels
         Exit Sub
     End If
     'Next line strPathAndFile contains path and filename of selected file ' < ======= FROM HERE
     strPathAndFile = .SelectedItems(1)
 End With

 'The following populates a cell with just the filename (without the path)
 strShortName = Right(strPathAndFile, Len(strPathAndFile) - _
         InStrRev(strPathAndFile, "\"))

 ' Store the path file in this cell
 ThisWorkbook.Worksheets("Sheet1").Range("F12") = strShortName

End Sub

第二部分 - 这里我想使用strPathAndFile变量。

 Sub CommandButton3_Click()
' Read a file and find the title name
' Variables
Dim WhatToFind As Variant
Dim wbFind As Workbook
Dim foundRange As Range

' Assign file path to a variable
Set wbFind = Workbooks.Open(strPathAndFile) ' <========  TO HERE

' Do not show actions on screen
Application.ScreenUpdating = False

' Array of valuse to be found
WhatToFind = Array("Dog", "House", "Table")

With wbFind.Sheets("general_report")
    Set foundRange = .Cells.Find(What:="status", After:=.Cells(1, 1), _
    LookIn:=xlFormulas, LookAt:=xlPart, SearchOrder:=xlByRows, _
    SearchDirection:=xlNext, MatchCase:=False, SearchFormat:=False)
End With

If Not foundRange Is Nothing Then foundRange.Activate

' close the source workbook without saving any changes
wbFind.Close False

' free memory
Set wbFind = Nothing

' Show actions on screen
Application.ScreenUpdating = False
End Sub

2 个答案:

答案 0 :(得分:2)

您已经在单元格中保存了路径,工作表(“Sheet1”)。范围(“F12”),你只是这样做

 ' Store the path file in this cell
 ThisWorkbook.Worksheets("Sheet1").Range("F12") = strPathAndFile

然后使用

 Dim fpath As String
 fpath = Worksheets("Sheet1").Range("F12").Value
 Set oWB = Application.Workbooks.Open(fpath)

答案 1 :(得分:1)

Public strFileAndPath As String

Sub getpath()
    Dim retvalue As String
    retvalue = ThisWorkbook.FullName
    strFileAndPath = retvalue
End Sub

你只需要设置strfileandpath全局变量,可以通过strFileAndPath = thisworkbook.fullname

来完成

上面的其他内容是我测试它。