ちなみにExcelの列とアクセスのテーブルのフィールド名は全く一緒です。
やりたいことは、
1.VBAでExcelの1行を読み取る。
Excelの列にIDがある。
アクセスのテーブルにもID列がある。
Excelで読み取ったIDがアクセス側にあれば、アップデートをかける。
IDがなければインサートを行う。
2.Excelの列とAccessのテーブルの列は同じフィールド名。
3.Excelで1行読み取ったら次の行へ。繰り返し。
ということをしたいです。次の行へはループでまわせばいいので理解できます。ただ、列数が100以上もあるので上のように列=値と1つ1つやっていると大変です。何かよい手はないでしょうか?
おそらく知りたい情報は動的にフィールド名を設定するということ。
sql = "UPDATE table SET " & Cells(i, 1) & " = '" & Cells(i, j) & "'"
objRS(Cells(i, 1)) = Cells(i, j)
という条件でupdate文なら
Dim lngRowCount as long lngRowCount = Excelのデータ行数 Dim lngColCount as long lngColCount = Excelデータ列数 Dim i as long for i = 2 to lngRowCount Dim sql as string sql = "UPDATE table SET " dim j as long for j = 2 to lngColCount sql = sql & Cells(1, j) & "='" & Cells(i,j) & "', " next j sql = sql & " WHERE id='" & Cells(i,1) & "'" debug.print sql next i
面倒なことを考えたくなかったらDAO.Recordsetで
Dim lngRowCount as long lngRowCount = Excelのデータ行数 Dim lngColCount as long lngColCount = Excelのデータ列数 Dim objRS as DAO.Recordset set objRS = CurrentDB.OpenRecordset("table") with objRS dim i as long for i = 2 to lngRowCount .findfirst("id ='" & Cells(i,1) & "'") if .nomuch then .addnew else .edit end if dim j as long for j = 2 to lngColCount .Fileds(Cells(1,j)) = Cells(i, j) next j .update .movefirst next i end with set objRS = nothing
accessとexcelが手元にないので動かなかったらごめんなさい。
ご回答ありがとうございます。考え方教えていたいて助かりました!