我需要运行一个VBScript,它可以动态设置SQL Server连接字符串,从Excel单元格中获取服务器名称和数据库名称,并刷新文件的所有工作表中的表格。
我目前有一个针对'刷新' '设置'上的按钮sheet(从服务器和数据库名称开始):
Sub Refresh_Click()
Dim Sh As Worksheet
Dim sServer As String
Dim sDatabase As String
Dim sTableName As String
Dim vDestinationRg As Variant
Dim sQuery(1 To 24) As String
Dim vQueryArray As Variant
Dim i As Integer
Dim j As Integer
Dim isSplit As Boolean
Dim sUsername As String
Dim sPassword As String
Set Sh = ActiveSheet
j = 1
isSplit = True
vQueryArray = Application.Transpose(Sh.Range("U1:U10"))
For i = LBound(vQueryArray) To UBound(vQueryArray)
If vQueryArray(i) <> "" Then
isSplit = False
sQuery(j) = sQuery(j) & Trim(vQueryArray(i)) & vbCrLf
ElseIf Not isSplit Then
isSplit = True
j = j + 1
End If
Next i
sServer = Sheets("Setup").Range("F5").Value
sDatabase = Sheets("Setup").Range("F7").Value
vDestinationRg = Array("$H$12")
sUsername = "username"
sPassword = "********"
For i = LBound(sQuery) To UBound(sQuery)
If sQuery(i) = "" Then Exit Sub
sTableName = "Result_Table_" & Replace(Replace(Sh.Name, " ", ""), "-", "") & "_" & i
On Error Resume Next
Sh.ListObjects(sTableName).Delete
On Error GoTo 0
With Sh.ListObjects.Add(SourceType:=0, Source:=Array( _
"OLEDB;Provider=SQLOLEDB.1;User Id=" & sUsername & "; Password=" & sPassword & ";Data Source=" & sServer & ";Initial Catalog=" & sDatabase & ""), Destination:=Sh.Range(vDestinationRg(i - 1))).QueryTable
.CommandText = sQuery(i)
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.PreserveColumnInfo = True
.ListObject.DisplayName = sTableName
.Refresh BackgroundQuery:=False
End With
Next
End Sub
我有一个用单元格写的选择查询&#34; U1&#34; &#39;设置&#39;表格,它创建并将表格填充到目标范围中,从&#34; H12&#34;开始。
但不是将查询放在&#39;设置&#39; sheet我想在不同的工作表上编写查询,这些工作表将填充相应工作表中的表,只需在Setup页面上单击一个Refresh按钮。
我该怎么做?
我被告知可以在不写VBScript的情况下实现,但没有运气!我尝试将SQL服务器连接添加到工作簿,但不能从那里使其动态化。