在大量 XLSB 文档中编辑连接字符串

Editing Connection String in a Boatload of XLSB Documents

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

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

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

所以三个问题:

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

$Fllt = gci "*.xlsb" -r

  1. 在 Excel
  2. 中打开它们

$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()

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