在file.txt中,我的引号如下所示
d:\ file.txt的:
"""\\server1\pc1\targetG0\source-pc\pkgs.gz"""
Run Code Online (Sandbox Code Playgroud)
我的目标是将D:\ file.txt中的行读入pFile参数
因此,我编写以下简单的VBA代码:
Dim pFile As String
Open "D:\file.txt" For Input As #1
Input #1, pFile
Close #1
MsgBox pFile
Run Code Online (Sandbox Code Playgroud)
我运行我的VBA代码但是从不清楚的原因pFile没有得到文件中的行内容,txt和MsgBox打印空盒子?
请告诉为什么pFile变为null?以及我需要在我的代码中修复的内容,以便将file.txt中的行放在pfile参数中
在文档中Input #,它声明:
您不应该编写包含嵌入式引号的字符串,例如,"1,2""X"用于Input#语句:Input#将此字符串解析为两个完整且独立的字符串.
所以这里发生的是你的字符串被解析为三个单独的字符串,因为你只使用一个变量作为参数Input #然后它只包含第一个(空)字符串.将代码稍微更改为以下内容:
Dim pFile As String
Dim pFile2 As String
Dim pFile3 As String
Open "D:\file.txt" For Input As #1
Input #1, pFile, pFile2, pFile3
Close #1
Run Code Online (Sandbox Code Playgroud)
结果如下:
pfile: (empty)
pfile2: \\server1\pc1\targetG0\source-pc\pkgs.gz
pfile3: (empty)
Run Code Online (Sandbox Code Playgroud)
如果你不能使用它,那么替代方法可以是使用类似于它的Line Input #语句(链接),Input #除了它不像(例如由于逗号/分隔符)界定行一样Input #.以下代码段:
Dim pFile As String
Open "D:\file.txt" For Input As #1
Line Input #1, pFile
Close #1
Run Code Online (Sandbox Code Playgroud)
结果如下:
pfile: """\\server1\pc1\targetG0\source-pc\pkgs.gz"""
Run Code Online (Sandbox Code Playgroud)
然后您可以根据自己的要求进行修改.