我对VBA很新,所以这可能是一个愚蠢的问题.. 我的userform上有2个按钮,一个用于搜索文件,另一个用于输入。 (这只是我正在做的事情的简化)。每次我收到错误'下标超出范围',但我不知道为什么。谁能帮帮我吗?非常感谢
Public file as Variant
Private Sub cmdBrowse_Click()
file = Application.GetOpenFilename
If file = False Then
MsgBox "There is no file selected.", vbCritical, "Warning"
End If
End Sub
Private Sub cmdInput_Click()
Cells(2, 2).Value = Workbooks(file).Worksheets(1).Cells(2, 2).Value
End Sub
答案 0 :(得分:0)
从Excel帮助 - “显示标准的”打开“对话框,从用户获取文件名,而不实际打开任何文件。您需要打开工作簿,如下所示:
Private Sub cmdBrowse_Click()
file = Application.GetOpenFilename
If file = False Then
MsgBox "There is no file selected.", vbCritical, "Warning"
Exit Sub
End If
Workbooks.Open file
End Sub
编辑:Application.Workbooks
属性不接受GetOpenFileName
返回的完整文件路径。所以在第二个子程序中,您不需要整个文件路径。您的代码应该从完整路径中提取文件的名称:
Private Sub cmdInput_Click()
Dim FileName as string
FileName = Mid(file,InStrRev(file,Application.PathSeparator)+1,99)
Cells(2, 2).Value = Workbooks(FileName).Worksheets(1).Cells(2, 2).Value
End Sub