繁体   English   中英

使用VBA将多个文本文件导入Excel中的1个单元格和新行?

[英]Import multiple text files to 1 cell and a new row in Excel using VBA?

我正在尝试将多个文本文件导入单元格A1,A2,A3等。这意味着文本文件1将转到A1文本文件2应该转到A2文本文件3应该转到A3

在stackoverflow上,我发现了一个代码 ,除了创建新列外,该代码几乎与我要执行的操作类似。

问题在于文件中的文本字符串已定界并放入新列中,因为这是代码的目的(使用答案中给出的替代方法)。

我不知道该代码中要进行什么更改,以将文件1的所有文本放入单元格A1中。 我希望有可能,如果没有的话,我希望您对其他解决方案有任何想法。

注释掉下面的代码行即可,因为curCol设置为1(即A列):

curCol = curCol + 1

我还想指出,链接到的代码效率很低,因为不需要在每次迭代之前测量底部的行。 确实应该使用一个变量来重写它,该变量只是将行号递增,改为:

nxt_row = nxt_row +1
ActiveSheet.Cells(nxt_row, curCol) = DataLine

并且以下代码行应移至子例程的开头:

if Range("A1").Value = "" then 
  nxt_row = 1
else
  if Range("A2").Value = "" then 
    nxt_row = 2
  else
     nxt_row = Range("A1").End(xlDown).Offset(1).Row
  end if
end if

如果希望将每个文件的全部内容放入单个单元格,则对您引用的代码进行以下修改可能会起作用:

Sub Import_All_Text_Files()

    Application.ScreenUpdating = False

    Dim thisRow As Long
    Dim fileNum As Integer
    Dim strInput As String

    Const strPath As String = "C:\Temp\Temp\"  'Change as required
    Dim strFilename As String

    strFilename = Dir(strPath & "*.txt")

    With ActiveSheet
        thisRow = .Range("A" & .Rows.Count).End(xlUp).Row

        Do While strFilename <> ""

            fileNum = FreeFile()
            Open strPath & strFilename For Binary As #fileNum
            strInput = Space$(LOF(fileNum))
            Get #fileNum, , strInput
            Close #fileNum

            thisRow = thisRow + 1
            .Cells(thisRow, 1).Value = strInput

            strFilename = Dir
        Loop
    End With

    Application.ScreenUpdating = True

End Sub

我不保证文件大小太大也可以使用-Excel对在一个单元格中可以插入多少个字符有限制(如果我没记错的话,可以插入32767个字符)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM