我有一个.bat文件,我用它来执行我从excel工作簿中提取的.vbs。
目前,我的.bat文件如下所示:
echo Starting program
start C:\Users\midi\Desktop\Refresh_Data_Connection.vbs
echo Finish program
但是,我的.vbs文件的问题在于它没有引用我需要它的特定工作簿。如何设置.vbs来更改存储在桌面上的特定工作簿?任何帮助/反馈或推进正确的方向都会非常有用,提前谢谢!
我的vbs是:
Sub RefreshConns()
With Application
.EnableEvents = False
.ScreenUpdating = False
End With
Sheets("Run Macro").Activate
Dim connName As String ' connection name
Dim connStr As String ' connection string
Dim sqltext ' SQL text
Dim TempconnName As String ' temporary connection name
Dim TempconnStr As String ' temporary connection string
Dim Tempsqltext ' temporary SQL text
Dim i As Integer
Dim SiteName As String
SiteName = ActiveSheet.Cells(1, 2)
'MsgBox (SiteName)
For i = 5 To 11
connName = ActiveSheet.Cells(i, 1).Value
connStr = ActiveSheet.Cells(i, 2).Value
sqltext = ActiveSheet.Cells(i, 4).Value
'MsgBox (connName)
TempconnStr = Replace(connStr, "SiteNameVBA", SiteName)
'Debug.Print (ActiveWorkbook.Connections(connName).ODBCConnection.Connection)
'MsgBox (TempconnStr)
'Tempsqltext = Replace(sqltext, "SiteNameVBA", SiteName)
'On Error Resume Next
ActiveWorkbook.Connections(connName).ODBCConnection.CommandText = sqltext
ActiveWorkbook.Connections(connName).ODBCConnection.Connection = "ODBC;" & TempconnStr
ActiveWorkbook.Connections(connName).Refresh
Next i
With Application
.EnableEvents = True
.ScreenUpdating = True
End With
End Sub
Public Function ZeroToBlank(x As String) As String
If x = "0" Then
ZeroToBlank = ""
Else
ZeroToBlank = x
End If
End Function
答案 0 :(得分:2)
一种方法是使用setx
声明系统环境变量。
使用管理权限运行批处理尝试:
setx PATHFILE "/path/file.xls" /M
检查是否声明:
set | find "PATHFILE"
使用函数Environ()
阅读它以在您的vbs中打开Workbook:
Workbooks.Open Environ("PATHFILE")
修改强>
您不需要使用系统环境变量(/m
参数),因为您只能使用用户环境。您需要记住,程序需要重新启动才能读取用户和系统环境变量。
答案 1 :(得分:1)
Set xlBook = GetObject("C:\Users\User\Documents\Super.xls")
For each wsheet in xlbook.worksheets
msgbox wsheet.name
next
是怎么回事。请记住,VBS中没有excel常量,没有dim x as something
因为vbs只有变体。所以只是dim x
。
运行excel副本的其他方法
Set GetExcelApp = GetObject("", "Excel.Application")
Msgbox GetExcelApp
启动一个新的Excel并显示一个excel常量,取而代之的是它的值(43)。
set xlapp = createobject("Excel.Application")
xlapp.Workbooks.Open "C:\Users\User\Documents\Super.xls"
'43 is 95/97 look up xlExcel9795 in object browser to see other options
xlapp.ActiveWorkbook.SaveAs "C:\Users\User\Documents\Super.xls", 43