vba – 从每个string数组中删除子string

我正在将一个文件夹的文件名存储到一个数组中。 然后,我试图从文件名中删除string中的“.xlsx”部分,并将其打印到电子表格中。 我很难从每个数组元素中删除“.xlsx”子string。 我被引导认为replacefunction是最好的,但还没有成功。 混淆领域由'HERE评论'HERE指出

 Sub Example() Dim FName As String 'Array to store filenames. Dim arNames() As String Dim myCount As Integer Dim i As Integer FName = Dir("G:\ExampleFolder\*.xls*") ' Run until there are no more filenames. Do Until FName = "" 'Increment myCount = myCount + 1 'Actively store filenames into an array. ReDim Preserve arNames(1 To myCount) arNames(myCount) = FName FName = Dir Loop 'Print array details to sheet. For i = LBound(arNames) To UBound(arNames) Next i 'Create a random excel sheet to print the file names. Set o = CreateObject("excel.application") ' Activate new excel spreadsheet. o.Visible = True o.Workbooks.Add 'Edit string in array. 'HERE Dim LResult As String 'LResult = Replace(arNames, ".xlsx", "") o.sheets("sheet1").Range("A1:" & ConvertToLetter(i) & "1").Value = arNames End Sub Function ConvertToLetter(iCol As Integer) As String Dim iAlpha As Integer Dim iRemainder As Integer iAlpha = Int(iCol / 27) iRemainder = iCol - (iAlpha * 26) If iAlpha > 0 Then ConvertToLetter = Chr(iAlpha + 64) End If If iRemainder > 0 Then ConvertToLetter = ConvertToLetter & Chr(iRemainder + 64) End If End Function 

原因是你正在尝试传递作为string数组的第一个参数的variablesarNames ,它应该是String (注意string数组和string之间的区别)。

您需要replace这些代码行:

 Dim LResult As String 'LResult = Replace(arNames, ".xlsx", "") 

与那一个:

 For i = LBound(arNames) To UBound(arNames) arNames(i) = Replace(arNames(i), ".xlsx", "") Next i 

你的Next i在错误的地方? 我假设你想从A1水平文本,取代'Print array details to sheet. 有:

 '// create an instance once; Set o = CreateObject("excel.application") o.Visible = True o.Workbooks.Add '// get the startcell Dim startCell As Range Set startCell = o.Sheets("sheet1").Range("A1") '// loop removing the extension and writing For i = LBound(arNames) To UBound(arNames) startCell.Offset(0, i - 1).Value = Mid$(arNames(i), 1, InStrRev(arNames(i), ".")) Next