我有vba宏(GetData),从sql中获取一些记录,将其放入表中,然后调用另一个宏(ConvertToCsv)将表转换为csv格式。
我的问题是csv文件缺少一些记录。
如果我运行转换宏,在GetData宏结束后,没有问题。
问题就在我调用GetData宏内部的Convert宏时。
代码示例:
获取记录宏
Sub getData()
.
.
comm.CommandText = _
"SELECT x, y, z FROM A"
rec.Open comm
If rec.EOF = True Then 'Check if there is any records
MsgBox ("There is no records")
Exit Sub
End If
row = 1
col = 1
Do While Not rec.EOF
WirteRecordsToSheets rec row col
col = 1
row = row + 1
rec.MoveNext
Loop
ActiveWorkBook.save
call ConvertToCsv
End Sub
Sub ConvertToCsv()
fRow = 1
fCol = 1
lCol = 20
filePath = "C:\aaa\bbb\"
fileName = "file.csv"
MakeDirectory filePath
Worksheets("1").Select
Set rng = Range(Cells(fRow, fCol), Cells(lRow, lCol))
rng.Value = Application.Trim(rng)
Set cpFromWB = ActiveWorkbook
' Set range to copy
With cpFromWB
'set the selected range
Set cpFromRng = Range(Cells(fRow, fCol), Cells(lRow, lCol))
End With
' Create new workbook
Set cpToWB = Workbooks.Add
Set cpToRng = cpToWB.ActiveSheet.Range("A1")
'Copy everything over to the new workbook
cpFromRng.Copy Destination:=cpToRng
' Save as CSV-file
Application.DisplayAlerts = False
ActiveWorkbook.SaveAs fileName:=filePath & fileName, FileFormat:=xlCSV, CreateBackup:=False
ActiveWorkbook.Close savechanges:=True
Application.DisplayAlerts = True
MsgBox ("the csv file named: " & fileName & " has successfully saved in the path: " & filePath)
End Sub
WirteRecordsToSheets(rec As Recordset, ByVal xlCol As Integer, ByVal xlRow As Integer)
Worksheets("1").Select
Cells(xlRow, xlCol).NumberFormat = "@"
Cells(xlRow, xlCol).Value = Trim(rec("x"))
xlCol = xlCol + 1
Cells(xlRow, xlCol).NumberFormat = "@"
Cells(xlRow, xlCol).Value = Trim(rec("y"))
xlCol = xlCol + 1
Cells(xlRow, xlCol).NumberFormat = "@"
Cells(xlRow, xlCol).Value = Trim(rec("z"))
End Sub
1条答案
按热度按时间8xiog9wr1#
使用CopyFromRecordset方法。