2015-12-17 147 views
0

我有一些簡單的代碼可以將所有數據從Excel表單加載到數組中,但我得到錯誤94 inproper use由於我的源代碼表有一些空白列IE:Q到EA是空白列,但A -P和EB-EF有數據。 (可怕的設計爲Excel表作爲我知道,但我沒有這樣做) 看到我不能重新設計表..我怎麼能跳過空白,以避免導致錯誤時,加載到他們我的數組?避免嘗試使用VBA和ADO/SQL將NULL值加載到數組中從Excel表單中提取數據

Dim Conn As New ADODB.Connection 
Dim mrs As New ADODB.Recordset 
Dim DBPath As String, sconnect As String 

DBPath = "\\MYPATH\MYFILE.xlsm" 
sconnect = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & DBPath _ 
& ";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=1"";" 

Conn.Open sconnect 
sSQLSting = "SELECT * From [log$]" 


    mrs.Open sSQLSting, Conn 
     '=>Load the Data into an array 
     ReturnArray = mrs.GetRows 

    'Close Recordset 
    mrs.Close 

'Close Connection 
Conn.Close 
+0

爲什麼然後'SELECT *'? – pnuts

+0

,因爲我動態加載工作表到這裏,它並不總是使用相同的東西。我只需要將工作表(表格)中的所有內容加載到我的數組中。 –

+0

我想我可以動態加載我的選擇語句..呃,儘管如此多的工作。 –

回答

1

IsNull()函數返回True或False。所以,包括它裏面的Jet/ACE的條件邏輯功能IIF()

sSQLString = "SELECT IIF(IsNull(Col1), 0, Col1)," _ 
       & " IIF(IsNull(Col2), 0, Col2)," _ 
       & " IIF(IsNull(Col3), 0, Col3)" 
       & " From [log$];" 
0

@JohnsonJason爲什麼你需要它的Array?你可以用Advanced Filter來篩選你的數據,比如here或者直接刪除它並循環獲取你需要的列。如果你不知道有多少列,你可以創建一個克隆Recordset並獲取列Name,並在此基礎上創建你的Query

克隆RecordSet是這樣的:

'' Declare Variables 
Dim oRst As ADODB.Recordset, oRstVal As ADODB.Recordset, oStrm As ADODB.Stream 
Dim sHeaders as String 

'' Set Variables 
Set oRst = New ADODB.Recordset 
Set oRstVal = New ADODB.Recordset 
Set oStrm = New ADODB.Stream 

.... [Something else] 
'' Save your current Recordset in the Stream 
oRst.Save oStrm 

'' Assign your Stream to the new Recordset (oRstVal) 
oRstVal.Open oStrm 

'' Loop trough your Recorset for Columns Name 
'' Use an IF or a Select to filter 
For iCol = 0 To oRstVal.Fields.Count - 1 
    sHeaders = sHeaders + "," + oRstVal.Fields(iCol).Name 
Next 

並使用你的聲明sHeaders在得到你需要的列。

''Instead of Select * From ... 
sQuery = "Select " + sHeaders + _ 
      "From ...." 
相關問題