excel - 将路径文件分配给VBA中的变量

标签 excel vba

我几乎完成了我程序的一小部分。我正在尝试将路径文件分配给变量,以便可以在第二部分中使用该变量,我尝试了以下方法。我很感激任何帮助。非常感谢您的先进

第一部分

 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

最佳答案

您已经将路径保存在单元格中,Worksheets("Sheet1").Range("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)

关于excel - 将路径文件分配给VBA中的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24248946/

相关文章:

arrays - 检查数组中的元素是否为 Null/Excel VBA

html - 单击 VBA 中图像的第二个按钮

c# - 是否可以使用 C# 在 excel 工作簿中编写功能

VBA : get Long limits programmatically

excel - 如何将保存到特定文件夹的多个文本文件导入到Excel中的一个工作表一列,每个文件的不同行?

excel - 尝试将使用复选框选中的行复制到另一个工作簿

excel - 复制/粘贴到多个单元格后类型不匹配?

Excel:计数 "Not equal to"

java - 使用 POI 删除 excel 中的一行

excel - 计算每个文件夹和子文件夹中有多少文件然后分别显示