You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

VBA批量导入TXT至独立工作表的代码问题求助

批量导入TXT文件到独立工作表(修正你的VBA代码)

你猜的没错!问题确实出在With语句里对location_string和data_name的使用方式上——你把变量用双引号括起来了,这会让VBA把它们当成字面字符串(也就是直接用"location_string"这个文本,而不是变量里存储的文件路径/工作表名称)。另外我还帮你优化了代码,去掉了不必要的Select/Activate操作,让代码更高效稳定。

修正后的完整代码

Sub Deneme_1()
    Dim location_string As String
    Dim data_name As String
    Dim wsVeri As Worksheet
    Dim newWs As Worksheet
    Dim i As Integer
    
    ' 提前引用Veri工作表,避免反复查找
    Set wsVeri = ThisWorkbook.Sheets("Veri")
    
    For i = 1 To 5
        ' 直接从Veri工作表读取数据,不用Select
        location_string = wsVeri.Range("B" & (i + 1)).Value
        data_name = wsVeri.Range("A" & (i + 1)).Value
        
        ' 添加新工作表并命名
        Set newWs = ThisWorkbook.Sheets.Add(After:=ThisWorkbook.Sheets(ThisWorkbook.Sheets.Count))
        newWs.Name = data_name
        
        ' 关键修正:去掉变量的引号,直接使用变量值
        With newWs.QueryTables.Add(Connection:= _
            location_string, Destination:=newWs.Range("$A$1"))
            .Name = data_name
            .FieldNames = True
            .RowNumbers = False
            .FillAdjacentFormulas = False
            .PreserveFormatting = True
            .RefreshOnFileOpen = False
            .RefreshStyle = xlInsertDeleteCells
            .SavePassword = False
            .SaveData = True
            .AdjustColumnWidth = True
            .RefreshPeriod = 0
            .TextFilePromptOnRefresh = False
            .TextFilePlatform = 65001
            .TextFileStartRow = 1
            .TextFileParseType = xlDelimited
            .TextFileTextQualifier = xlTextQualifierDoubleQuote
            .TextFileConsecutiveDelimiter = False
            .TextFileTabDelimiter = True
            .TextFileSemicolonDelimiter = False
            .TextFileCommaDelimiter = True
            .TextFileSpaceDelimiter = False
            .TextFileColumnDataTypes = Array(1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, _
                1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 _
                , 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1)
            .TextFileTrailingMinusNumbers = True
            .Refresh BackgroundQuery:=False
        End With
    Next i
End Sub

关键修改点说明

  • 去掉变量的引号:原来的"location_string"和"data_name"改成直接用location_string和data_name,这样VBA才会读取变量中存储的实际路径和名称。
  • 避免Select/Activate:直接引用工作表对象(比如wsVeri和newWs),这是VBA的最佳实践,能避免因工作表切换导致的错误,同时提升代码运行速度。
  • 明确指定新工作表:添加新工作表后直接赋值给newWs,后续操作都基于这个对象,逻辑更清晰。

如果你的实际文件数量是250个,可以把循环的To 5改成To 250,或者更灵活一点,通过判断Veri工作表的最后一行来自动确定循环次数(比如wsVeri.Cells(wsVeri.Rows.Count, "A").End(xlUp).Row - 1,因为你是从第2行开始读的)。

内容的提问来源于stack exchange,提问作者Seqenenre Tao

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.09 08:02:29