我有VBA宏(GetData),它从sql中获取记录,将其放入工作表中,然后调用另一个宏(ConvertToCsv),将工作表转换为csv格式。
如果我在GetData宏之后运行convert宏,则没有问题。
当我调用Convert宏时,GetData宏中csv文件丢失了一些记录。
获取记录宏
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条答案
按热度按时间uurv41yg1#
使用CopyFromRecordset方法。