C# 用VB.NET编辑Excel连接字符串

C# 用VB.NET编辑Excel连接字符串,c#,excel,vb.net,C#,Excel,Vb.net,我们的excel文件使用外部数据链接数据库服务器。 最近,我们公司更改了数据库服务器并将其迁移到新服务器 由于旧服务器名称不存在,所有excel文件无法连接到数据库。 因此,我需要打开excel文件,连接字符串将服务器名称从旧更改为新。 但是有一百多个excel需要更改连接字符串,因此我开始考虑使用VB.NET制作一个程序来批量更改excel连接字符串 这可能吗? 这可以节省我逐个更改excel文件的时间。这是很常见的,您可以修改现有代码以满足您的需要: 顺便说一下,您将使用的是Excel VB

我们的excel文件使用外部数据链接数据库服务器。 最近,我们公司更改了数据库服务器并将其迁移到新服务器

由于旧服务器名称不存在,所有excel文件无法连接到数据库。 因此,我需要打开excel文件,连接字符串将服务器名称从旧更改为新。 但是有一百多个excel需要更改连接字符串,因此我开始考虑使用VB.NET制作一个程序来批量更改excel连接字符串

这可能吗?
这可以节省我逐个更改excel文件的时间。

这是很常见的,您可以修改现有代码以满足您的需要:

顺便说一下,您将使用的是Excel VBA,而不是VB.Net

Private Sub Workbook_Open()

Dim conn As WorkbookConnection
Dim sOldConnection As String, sNewConnection As String
Dim sOldPath As String
Dim sNewPath As String
Dim sLength As Integer
Dim sOldPath1 As String
Dim intDsnLen As Integer
Dim intDsnStart As Integer
Dim intDsnEnd As Integer

'I first check if there is a folder called "Analysis" as this is what we generally use to store our analysis tools.
If InStr(1, Application.ThisWorkbook.Path, "Analysis") > 0 Then
'I then remove that from the path that I require
sLength = Len(Application.ThisWorkbook.Path) - 9
'I set the new path to the workbook path minus the analysis folder and the "\"
sNewPath = Left(Application.ThisWorkbook.Path, sLength)
Else
'If the folder doesn't exist, I then set the new part to the excel workbooks path
sLength = Len(Application.ThisWorkbook.Path)
sNewPath = Left(Application.ThisWorkbook.Path, sLength)
End If

For Each conn In ActiveWorkbook.Connections
With conn
If .Type = xlConnectionTypeODBC Then
sOldConnection = .ODBCConnection.Connection

'I used these steps to find my specific connection string....not the best way to use it but I was getting
'a bit irritated with the fact that instr doesn't remove all that I don't require.
'In my case, this will always work...may not for others but you can always play around to find your best fit.
intDsnStart = InStr(1, sOldConnection, "DBQ") + 3
intDsnEnd = InStr(intDsnStart, sOldConnection, "Reports.MDB")
intDsnLen = intDsnEnd - intDsnStart
'I get my old path in my old connection..I need this specifically as I want to replace it
sOldPath = Mid(sOldConnection, intDsnStart + 1, intDsnLen - 2)

'Here, I replace the old path with the new path, irrespective of whether it is the same or not in my new connection
sNewConnection = Replace(sOldConnection, _
sOldPath, sNewPath, Compare:=vbTextCompare)
'I set the odbc connection to my new built connection and then refresh
.ODBCConnection.Connection = sNewConnection
.Refresh

End If
End With
Next conn

Set conn = Nothing
代码取自此处:


这是很常见的,您可以修改现有代码以满足您的需要:

顺便说一下,您将使用的是Excel VBA,而不是VB.Net

Private Sub Workbook_Open()

Dim conn As WorkbookConnection
Dim sOldConnection As String, sNewConnection As String
Dim sOldPath As String
Dim sNewPath As String
Dim sLength As Integer
Dim sOldPath1 As String
Dim intDsnLen As Integer
Dim intDsnStart As Integer
Dim intDsnEnd As Integer

'I first check if there is a folder called "Analysis" as this is what we generally use to store our analysis tools.
If InStr(1, Application.ThisWorkbook.Path, "Analysis") > 0 Then
'I then remove that from the path that I require
sLength = Len(Application.ThisWorkbook.Path) - 9
'I set the new path to the workbook path minus the analysis folder and the "\"
sNewPath = Left(Application.ThisWorkbook.Path, sLength)
Else
'If the folder doesn't exist, I then set the new part to the excel workbooks path
sLength = Len(Application.ThisWorkbook.Path)
sNewPath = Left(Application.ThisWorkbook.Path, sLength)
End If

For Each conn In ActiveWorkbook.Connections
With conn
If .Type = xlConnectionTypeODBC Then
sOldConnection = .ODBCConnection.Connection

'I used these steps to find my specific connection string....not the best way to use it but I was getting
'a bit irritated with the fact that instr doesn't remove all that I don't require.
'In my case, this will always work...may not for others but you can always play around to find your best fit.
intDsnStart = InStr(1, sOldConnection, "DBQ") + 3
intDsnEnd = InStr(intDsnStart, sOldConnection, "Reports.MDB")
intDsnLen = intDsnEnd - intDsnStart
'I get my old path in my old connection..I need this specifically as I want to replace it
sOldPath = Mid(sOldConnection, intDsnStart + 1, intDsnLen - 2)

'Here, I replace the old path with the new path, irrespective of whether it is the same or not in my new connection
sNewConnection = Replace(sOldConnection, _
sOldPath, sNewPath, Compare:=vbTextCompare)
'I set the odbc connection to my new built connection and then refresh
.ODBCConnection.Connection = sNewConnection
.Refresh

End If
End With
Next conn

Set conn = Nothing
代码取自此处:


我需要感谢@GoodJuJu建议我使用Excel VBA。 但是这个函数并不是我想要的

所以我花了一天的时间研究我自己的功能

此函数可以替换文件夹和子文件夹中的所有excel连接字符串

下面的代码,我已经从网站复制了搜索文件夹的功能

只需更改函数connstrrereplacer()中的“targetName”和“cvtFrom”和“cvtTo”。 示例我的连接需要将“ServerName”从SERVER01更改为SERVER02 所以targetName=“ServerName”,cvtFrom=“SERVER01.1583”,cvtTo=“SERVER02.1583”

希望这能帮助其他同样需要这种功能的人

DSN=全局_TST;ServerName=SERVER01.1583;UID=主机;ArrayFetchOn=1;ArrayBufferSize=8;TransportHint=TCP:SPX;DBQ=全球温度;ClientVersion=12.11.025.000;CodePageConvert=1252;PvClientEncoding=CP1252;PvServerEncoding=CP1252;AutoDoubleQuote=0

公共计数为整数
'从中复制源https://exceloffthegrid.com/vba-code-loop-files-folder-sub-folders/
子循环所有子文件夹SelectStartDirectory()
Dim FSOLibrary作为文件系统对象
作为对象的模糊文件夹
Dim folderName作为字符串
计数=3
附页1
'删除Sheet1中的旧记录
.范围(“A:D”)。删除
'设置记录的标题
.Range(“A”和count).Value=“匹配”
.Range(“B”和count).Value=“已替换”
.Range(“C”和count).Value=“连接”
.Range(“D”和count).Value=“文件路径”
'设置格式和样式
.范围(“A:C”).水平对齐=xlCenter
.Range(“A:C”).Columns.AutoFit
以
'将文件夹名称设置为变量
folderName=ActiveWorkbook.Path
'设置对FSO库的引用
Set FSOLibrary=新文件系统对象
'另一个宏必须调用LoopAllSubFolders宏才能启动
LoopAllSubFolders FSOLibrary.GetFolder(folderName)
MsgBox(“完成!”)
端接头
'从中复制源https://exceloffthegrid.com/vba-code-loop-files-folder-sub-folders/
子循环所有子文件夹(FSOFolder作为对象)
将FSOSubFolder设置为对象
作为对象的Dim FSOFile
作为对象的Dim fso
设置fso=CreateObject(“Scripting.FileSystemObject”)
'对于每个子文件夹,调用宏
对于FSOFolder.SubFolders中的每个FSOSubFolder
LoopAll子文件夹FSOSUBFolders
下一个
'打印每个文件的名称
对于FSOFolder.Files中的每个FSOFile
'插入要对每个文件执行的操作
'此示例将打印即时窗口的完整文件路径
Dim ext作为字符串
ext=fso.GetExtensionName(FSOFile.Path)
'将扩展名与excel文件匹配
'跳过隐藏的excel文件->左侧(FSOFile.Name,1)“~”
如果(ext=“xlsm”或ext=“xlsx”或ext=“xls”)和左(FSOFile.Name,1)“~”则
'调用函数并用路径传递excel文件名
连接替换程序(FSOFile.Path)
如果结束
下一个
端接头
子连接替换程序(文件名为字符串)
Dim newWB,actWB作为工作簿
作为工作簿连接的Dim conn
Dim targetName,cvtTo作为字符串
Dim cvtFrom,状态为变量
'连接字符串中的名称
targetName=“服务器名”
'匹配目标名称的值列表
cvtFrom=阵列(“HFBE-DC01-SVR.1583”、“192.168.0.4.1583”)
'如果该值与上述列表匹配,则替换为该值
cvtTo=“HFBE-GSS01-VM.1583”
'声明活动工作簿
设置actWB=ActiveWorkbook
'如果与当前excel相同,则跳过
如果文件名=(actWB.Path&“\”&actWB.Name),则退出Sub
'将结果记录到表1中
计数=计数+1
附页1
.Range(“A”和count).Value=“?”
.Range(“B”和count).Value=“?”
.Range(“C”和count).Value=“?”
.Range(“D”&count).Value=文件名
以
应用
.Calculation=xlCalculationManual
.ScreenUpdate=False
.EnableEvents=False
以
'如果无法打开excel,则跳过(Exp:excel受保护)
出错时继续下一步
'如果是excel文件,则打开文件
Set newWB=Workbooks.Open(文件名,False,False,“”)
错误转到0
'newWB为空表示无法打开excel
如果是空的(新WB)Th