我正在处理一些vba,它会根据工作簿中选定的报表和过滤器改变odbc连接字符串。 vba的核心工作绝对正常,但现在我想做以下事情:
我的vba是最好的平均值,所以我对第1点和第1点都不错。 3但是无法弄清楚第2部分并希望得到一些帮助。
这是vba的代码,当一个表已经存在时,该代码链接到连接字符串时非常有效:
Sub ODBC_RUN_REPORT()
ThisWorkbook.Activate
Dim jdeSystem As String
Dim jdecorelib As String
Dim jdeUDClib As String
Dim jdeGSClib As String
Dim jdeIBANlib As String
Dim jdeQUERYlib As String
Dim odbcConnection As odbcConnection
Dim connection_string As String
Dim commandtext1 As String
Dim commandtext2 As String
Dim commandtext3 As String
Dim commandtext4 As String
Dim commandtext5 As String
Dim commandtext6 As String
Dim commandtext7 As String
Dim commandtext8 As String
Dim commandtext9 As String
Dim commandtext10 As String
jdeSystem = Range("NR_CONSTR_ENV").Text
jdecorelib = Range("NR_CONSTR_CORE_LIB").Text
jdeUDClib = Range("NR_CONSTR_UDC_LIB").Text
jdeGSClib = Range("NR_CONSTR_GSC_LIB").Text
jdeIBANlib = Range("NR_CONSTR_IBAN_LIB").Text
jdeQUERYlib = Range("NR_CONSTR_QUERY_LIB").Text
connection_string = "ODBC;DRIVER={Client Access ODBC Driver (32-bit)};CONNTYPE=2;TRANSLATE=1;NAM=1;QRYSTGLMT=-1;PKG=QGPL/DEFAULT(IBM),2,0,1,0,512;LANGUAGEID=ENU;DFTPKGLIB=QGPL;DBQ=" + jdecorelib + " " + jdeUDClib + " " + jdeGSClib + " " + jdeIBANlib + " " + jdeQUERYlib + ";SYSTEM=" + jdeSystem + ";"
commandtext1 = Range("NR_CMD_TXTQ1").Text
commandtext2 = Range("NR_CMD_TXTQ2").Text
commandtext3 = Range("NR_CMD_TXTQ3").Text
commandtext4 = Range("NR_CMD_TXTQ4").Text
commandtext5 = Range("NR_CMD_TXTQ5").Text
commandtext6 = Range("NR_CMD_TXTQ6").Text
commandtext7 = Range("NR_CMD_TXTQ7").Text
commandtext8 = Range("NR_CMD_TXTQ8").Text
commandtext9 = Range("NR_CMD_TXTQ9").Text
commandtext10 = Range("NR_CMD_TXTQ10").Text
Set odbcConnection = ThisWorkbook.Connections("ODBC_RUN_REPORT").odbcConnection
odbcConnection.Connection = connection_string
odbcConnection.CommandText = commandtext1 + commandtext2 + commandtext3 + commandtext4 + commandtext5 + commandtext6 + commandtext7 + commandtext8 + commandtext9 + commandtext10
odbcConnection.Refresh
'注意 - 此处的所有内容都是vba代码的一部分,但保留导出到新工作簿的版本并不重要。
Sheets("USER CONTROL").Select
Range("D14").Select
MsgBox "Report Refresh Complete"
End Sub
答案 0 :(得分:0)
运行一个宏记录,记录创建新工作表(尚未工作簿!),并将其附加到数据库/数据源中的某些数据上。您最终会遇到类似这样的事情...
var processors = helper.Query("SELECT * FROM Win32_Processor");
这应该使您将数据放入当前工作簿的新工作表或现有工作表中。
现在使用类似的方法将数据或表复制/移动到新工作簿中...
With ActiveSheet.ListObjects.Add(SourceType:=0, Source:= _
"ODBC;DSN=xxx;Description=xxxx;UID=xxxx;;APP=Microsoft Office 2016;WSID=xxxx;DATABASE=xxxx;LANGUAGE=us_english" _
, Destination:=Range("$A$1")).QueryTable
.CommandType = 0
.CommandText = Array("SELECT * FROM dbo.myTable"
.RowNumbers = False
.FillAdjacentFormulas = False
.PreserveFormatting = True
.RefreshOnFileOpen = False
.BackgroundQuery = True
.RefreshStyle = xlInsertDeleteCells
.SavePassword = False
.SaveData = True
.AdjustColumnWidth = True
.RefreshPeriod = 0
.PreserveColumnInfo = True
.ListObject.DisplayName = "Table_Query_from_SPOT"
.Refresh BackgroundQuery:=False
End With