VBScript,将文本文件加载到数组并分配给变量



嘿,脚本天才们,请注意,我仍在学习VBScript,我已经做好了充分的准备。所以,只要我有方向,我会研究你要求我做的任何事情。

我搜索了建议的问题,发现了一个可能是我需要的问题,但它是"关闭的",没有链接可以去寻找其他类似的问题。

以下是我正在努力实现的目标。我需要获取一个文本文件并将数据加载到一个数组中(如果这是正确的)。此数据包含Pc名称、Pc位置。它将携带大约2000条记录(或行),我需要将每条记录加载到一个变量中。电脑名称没有空格,但电脑位置可以。例如:

Laptop, my bathroom 
Desktop, kitchen 

我想将这些信息加载到一个变量中,我可以使用WshShell.SendKeys并传递密钥命令。我已经能够让它"有点"与两个文本文件一起工作,并将数据发送到excel表中(因为它可以进行制表和输入)。但它不是一比一,而是一比十。因此,如果PC.txt有10个电脑名称,Location.txt有10个位置(按行顺序与每个文件匹配),我的脚本会给我100个结果,而不是10个。所以,我知道我做错了,需要一些指导。这是我失败的尝试,我已经准备好接受笑声了。。

Set WshShell = WScript.CreateObject("WScript.Shell")
Set objFSO = CreateObject("Scripting.FileSystemObject")
Set objFile1 = objFSO.OpenTextFile("C:pc.txt", ForReading1)
Set objFile = objFSO.OpenTextFile("C:Location.txt", ForReading)
'test is my excel file title test, this will allow tabs and enters
WshShell.AppActivate "test"
Const ForReading1 = 1
Dim arrFileLines1()
i = 0
Do Until objFile1.AtEndOfStream
Redim Preserve arrFileLines1(i)
arrFileLines1(i) = objFile1.ReadLine
i = i + 1
Loop
objFile1.Close
Const ForReading = 1
Dim arrFileLines()
i = 0
Do Until objFile.AtEndOfStream
Redim Preserve arrFileLines(i)
arrFileLines(i) = objFile.ReadLine
i = i + 1
Loop
objFile.Close
For Each strLine1 in arrFileLines1
For Each strLine in arrFileLines
WshShell.SendKeys strLine1
WshShell.SendKeys "{TAB}"
WshShell.SendKeys strLine
WshShell.SendKeys "{ENTER}"
Next
Next

我一直在研究如何根据"来分割这些数据,但我需要将其转换为一个变量,我可以使用它并重复按键,比如:

笔记本电脑{TAB}我的厨房{ENTER}桌面{TAB}浴室{ENTER}…………..等等,直到最后。

我会使用一个循环和一个字典将两个输入文件加载到一个数据结构中(假设PC名称是唯一的)。

Const ForReading = 1
Set fso = CreateObject("Scripting.FileSystemObject")
Set names     = fso.OpenTextFile("C:pc.txt", ForReading)
Set locations = fso.OpenTextFile("C:Location.txt", ForReading)
Set computers = CreateObject("Scripting.Dictionary")
Do Until names.AtEndOfStream Or locations.AtEndOfStream
computers.Add names.ReadLine, locations.ReadLine
Loop
names.Close
locations.Close

这将创建一个具有名称/位置对的字典,可以像这样访问:

For Each key In computers
WScript.Echo key & " is in " & computers(key)
Next

不过,我建议在向其他应用程序传递数据时不要使用SendKeys,因为至少可以说,该函数的使用往往很不稳定。根据目标应用程序的不同,可能有更好的方法,例如,如果应用程序公开了可以从VBScript控制的COM对象。

如果目标应用程序不能是RC,那么你最好使用AutoIt,就像其他人已经建议的那样。

最新更新