从范围创建数组,同时忽略空格

时间:2015-04-24 13:01:05

标签: arrays excel vba blank-line

我正在努力做一些基本的事情......

使用Excel VBA: 需要从范围(1维)创建数组,但该过程需要删除任何空格。

我的代码无效...

Sub ReadFilePaths()

Dim b As Long 'counter
Dim rPATHS As Range 'selected range containing file paths
Dim aTEMP As Variant 'initial array to be cleaned of blanks
Dim aFILEPATHS As Variant 'final array containing File Paths of those to be ReFlagged

Sheets("FILES").Select 'select ws where they are listed
Range("B3:B33").Select 'select range of them (30 files max)
Set rPATHS = Selection 'sets range rPATHS to the selection

aTEMP = rPATHS.Value 'Temp Array set to values in list

For b = LBound(aTEMP) To UBound(aTEMP)
        If aTEMP(b) = "" Then
        End If
     aFILEPATHS = aTEMP(b)
Next b
End Sub

我今天有一天这样!非常感谢任何帮助。

数据输入将是

Element
C:\Test\myfile1.txt
C:\Test\myfile2.txt

E:\Folder1\Folder2\hisfile1.txt

F:\FolderA\herfile2.txt
C:\FolderC\zfileAV.txt

数组输出

C:\Test\myfile1.txt
C:\Test\myfile2.txt
E:\Folder1\Folder2\hisfile1.txt
F:\FolderA\herfile2.txt
C:\FolderC\zfileAV.txt

2 个答案:

答案 0 :(得分:2)

在我看来,你无法使用范围创建一维数组。

如果使用范围来辅助数组,则创建二维数组 - 在您的示例aTEMP(1 to 31, 1 to 1)中。尝试使用小修正此代码:

Sub ReadFilePaths()

Dim b As Long 'counter
Dim rPATHS As Range 'selected range containing file paths
Dim aTEMP() As Variant 'initial array to be cleaned of blanks
Dim aFILEPATHS() As Variant 'final array containing File Paths of those to be ReFlagged
Dim i As Long
Sheets("FILES").Select 'select ws where they are listed
Range("B3:B33").Select 'select range of them (30 files max)
Set rPATHS = Selection 'sets range rPATHS to the selection

aTEMP = rPATHS.Value 'Temp Array set to values in list

For b = LBound(aTEMP) To UBound(aTEMP)
        If aTEMP(b, 1) <> vbNullString Then
        ReDim Preserve aFILEPATHS(i)
        aFILEPATHS(i) = aTEMP(b, 1)
        i = i + 1
        End If
Next b

End Sub

答案 1 :(得分:0)

您正在测试他们是空白,但对此无所作为,请尝试此操作。

Sub ReadFilePaths()
    Dim b As Long               'counter
    Dim rPATHS As Range         'selected range containing file paths
    Dim aTEMP As Variant        'initial array to be cleaned of blanks
    Dim aFILEPATHS As Variant   'final array containing File Paths of those to be ReFlagged
    Dim tmpStr As String        'Temporary String

    Sheets("FILES").Select      'select ws where they are listed
    Range("B3:B33").Select      'select range of them (30 files max)
    Set rPATHS = Selection      'sets range rPATHS to the selection

    aTEMP = rPATHS.Value        'Temp Array set to values in list

    For b = LBound(aTEMP) To UBound(aTEMP)
        If Len(aTEMP(b) & vbNullString) <> 0 Then
            tmpStr = tmpStr & aTEMP(b) & "#"
        End If
    Next b

    aFILEPATHS = Split(tmpStr, "#")
End Sub