我正在尝试在我的Excel工作表中实现一个命令按钮,该按钮将提示用户在将所选文件加载到指定单元格之前选择要加载的文件。到目前为止,我已尝试使用以下代码,但无济于事。我收到了type 13
错误
Sub check11()
Dim FileName() As Variant
Dim f As String
Dim i As Variant
Dim j As Variant
Dim rng As Variant
rng = ActiveCell.Address
f = Application.GetOpenFilename("TXT File (*.txt), *.txt")
For i = 0 To 1
FileName(f) = j
Range(rng).Value = j
ActiveCell.Offset(1, 0).Select
Next i
End Sub
答案 0 :(得分:0)
GetOpenFileName
无法按照您编码的方式运行。您无法选择多个文件(据我所知),因此您运行的循环是多余的。如果用户点击取消或该文件的名称为字符串,该函数将返回False
。您应该在代码中测试Cancel案例。
我无法看到循环的目的或为什么选择偏移单元格。我认为这可能是一个开发错误,所以我只是忽视了它。
下面是一些代码,向您展示GetOpenFileName
函数如何在您的上下文中起作用:
Sub check11()
Const TARGET_COL As String = "A" 'adjust letter for your column
Dim ws As Worksheet
Dim selectedFile As Variant
Dim cell As Range
'Find the next blank cell in target column
Set ws = ThisWorkbook.Worksheets("Sheet1")
Set cell = ws.Cells(ws.Rows.Count, TARGET_COL).End(xlUp).Offset(1)
'Open the file dialog window
selectedFile = Application.GetOpenFilename("Text Files (*.txt), *.txt")
'Check if user hit cancel
If selectedFile = False Then Exit Sub
'Write the file name
cell.Value = selectedFile
End Sub
答案 1 :(得分:0)
您首先需要将Application.GetOpenFilename
设置为MultiSelect
,因此您可以选择多个文件。然后这个函数将返回你可以循环的数组。在循环中我用“\”分割文件路径并且知道文件名总是最后的,我只是将文件名写入单元格。
Sub check11()
Dim filePath() As Variant
Dim i As Long
filePath = Application.GetOpenFilename("TXT File (*.txt), *.txt", MultiSelect:=True)
For i = 1 To UBound(filePath)
Sheets("Sheet2").Cells(1 + i, 1).Value = Split(filePath(i), "\")(UBound(Split(filePath(i), "\")))
Next i
End Sub