避免尝试使用VBA和ADO / SQL将NULL值加载到数组中以从Excel工作表中提取数据

时间:2015-12-17 21:34:51

标签: arrays excel vba ado

我有一些简单的代码可以将excel表中的所有数据加载到数组中,但由于我的源表有一些空白列IE:Q到EA,因此我得到错误94正确使用null空白列,但A -P和EB - EF有数据。 (我知道,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

2 个答案:

答案 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$];" 

答案 1 :(得分:0)

@JohnsonJason为什么你需要Array?您只需使用Advanced Filter Recordset来过滤数据,或者只需将其删除并循环即可获得所需的列。如果您不知道有多少列,则可以创建克隆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

在Statement中使用''Instead of Select * From ... sQuery = "Select " + sHeaders + _ "From ...." 来获取所需的列。

ALTER TABLE `sales_order` CHANGE `delivery_date` `delivery_date` DATE;