我试图将文本文件的内容加载到变量中,但是我得到了名义错误,搜索VBA知识库让我相信那个
Set mySQL = My.Computer.FileSystem.ReadAllText("C:\sql_query_temp.res")
会解决它,但只是在我运行时产生'错误:需要对象'。继承我的代码,我错过了什么?
'Requires Microsoft ActiveX Data Objects x.x library in references
Public Sub ConnectToOdbc()
Dim myconn As New ADODB.Connection
Dim myrs As New Recordset
Dim mySQL As String
Dim myrows As Long
'Open file containing SQL query
mySQL = My.Computer.FileSystem.ReadAllText("C:\sql_query_temp.res") <----- bad!
'Open Connection
myconn.Open "DSN=database"
'Do Query
myrs.Source = mySQL
Set myrs.ActiveConnection = myconn
myrs.CursorLocation = adUseClient
myrs.Open
'Count Rows
myrows = myrs.RecordCount
'Add text to word document!
Selection.TypeText (myrows)
'Close Connection
myrs.Close
myconn.Close
End Sub
答案 0 :(得分:2)
My.Computer
是VB.NET,它与VBA
完全不同,而你可以;
Function readFile(path As String) As String
Dim hF As Integer
hF = FreeFile()
Open path For Input As #hF
readFile = Input$(LOF(hF), #hF)
Close #hF
End Function
...
mySQL = readFile("C:\sql_query_temp.res")
答案 1 :(得分:0)
我认为这可能有用。
它允许您搜索任何给定的目录,而不是只注意那个目录。然后将此目录放在变量'inFileName'
上 inFileName = Application.GetOpenFilename("Text & r01 Files(*.*),*.*", , "Open Neutral File", "OPEN)
希望这有帮助。