将文件名称导入Excel单元格

我试图在我的Excel工作表中实现一个命令button,提示用户在将所选文件加载到指定的单元格之前select他要加载的文件。 到目前为止,我已经尝试使用下面的代码,但无济于事。 我得到了一个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 

GetOpenFileName不能以你编码的方式工作。 你不能select多个文件(据我所知),所以你运行的循环是多余的。 如果用户点击取消或文件的名称作为string,该函数将返回False 。 你应该在代码中testingCancel的情况。

我看不到你的循环的目的或为什么你select偏移单元格。 我认为这可能是一个发展的错误,所以我只是无视它。

下面是一些代码,告诉你如何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 

你有inccorect访问Application.GetOpenFilename首先你需要设置MultiSelect为true,所以你将能够select多个文件。 然后这个函数会返回你可以循环的数组。 在循环我分裂文件path的“\”和知识文件名总是最后,我只是写入文件名单元格。

 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