1

我有几百个 .xlsb 文件,它们需要以易于编程的方式更改它们的连接字符串和命令文本。它们都埋在文件系统深处的不同文件夹中。如何使用 Powershell 或其他一些程序来完成并编辑它们,这样我就不必手动进行了?

我已经开始研究 Powershell 和 Format-Hex。我想我可以问,其他人也许可以让我走上正确的道路。需要做的是从某个点递归搜索文件系统,检测“这个字符串”和这个数字“11111”是否在所有xlsb文件的连接字符串和命令文本中(分别),如果它们被替换为“那个字符串”和这个数字“22222”。全部在 xlsb 文件中。我也研究过使用 python,但我发现的库没有提到编辑这个设置,所以我认为某种十六进制检测和替换会更容易。

4

1 回答 1

0

是否有可能获得有关什么是“连接字符串”的更多信息?据我所知,这不是 xlsb 文件属性的一部分。我想它是用于创建 ODBC 连接的字符串,因此您要修改的文本将在宏的代码中。

所以三个问题:

  1. 递归查找文件夹中的所有 xlsb 文件

$Fllt = gci "*.xlsb" -r

  1. 在 Excel 中打开它们

$Excl = New-Object -ComObject Excel.Application

$Fllt | %{$xl.Workbooks.Open($_.Fullname)}

  1. 在每个宏中将“this string”替换为“that string”,将“11111”替换为“22222”。这要困难得多。

我的建议:

#Generation of a test file
$Excl = New-Object -ComObject Excel.Application
$xlve = $Excl.Version
New-ItemProperty -Path "HKCU:\Software\Microsoft\Office\$xlve\Excel\Security" `
    -Name AccessVBOM -Value 1 -Force | Out-Null
New-ItemProperty -Path "HKCU:\Software\Microsoft\Office\$xlve\Excel\Security" `
    -Name VBAWarnings  -Value 1 -Force | Out-Null
@'
Sub Co()
ConnectionString = "this string"
CommandText = "11111"
End Sub
'@ | Out-File C:\Temp\Test.txt -Encoding ascii
$Wkbk = $Excl.Workbooks.Add()
$Wkbk.VBProject.VBComponents.Import("C:\Temp\Test.txt") | Out-Null
$Wkbk.SaveAs("C:\Temp\Test.xlsb", 50)
$Excl.Quit()

#Get The files
$Fllt = gci -Path C:\Temp\ -Include *.xlsb -r

#Open Excel and set the security parameters to be able to modify macros
$Excl = New-Object -ComObject Excel.Application
$xlve = $Excl.Version
New-ItemProperty -Path "HKCU:\Software\Microsoft\Office\$xlve\Excel\Security" `
    -Name AccessVBOM -Value 1 -Force | Out-Null
New-ItemProperty -Path "HKCU:\Software\Microsoft\Office\$xlve\Excel\Security" `
    -Name VBAWarnings  -Value 1 -Force | Out-Null


#Loop through the files and modify the macros
$path = "C:\Temp\ModuleVBATemp.txt" #Temp text file to copy and modify the macros 
foreach ($File in $Fllt) {
$Wkbk = $Excl.Workbooks.Open($File.Fullname)
if ($Wkbk.HasVBProject) <# Test if any macro #> {
foreach ($Vbco in $Wkbk.VBProject.VBComponents) {
if ($Vbco.Type -eq '1') <# Only modify the modules #> {
    #Modification of the script
    $Vbco.Export($path) | Out-Null
    (gc $path) -replace "this string","that string" -replace "11111","22222" `
      | Out-File $path -Encoding ascii
    $Wkbk.VBProject.VBComponents.Remove($Vbco)
    $Wkbk.VBProject.VBComponents.Import($path) | Out-Null
}}}
$Wkbk.Close($true) #Save the file
}
$Excl.Quit()

它正在处理我的测试文件,我希望你的配置是相似的。

于 2019-05-10T18:21:15.837 回答