第一次在这里问任何问题,我被指派用 VBA 做一些事情,尽管我没有这方面的经验(我也从未声称有任何经验)。我已经阅读了其他文章,这些文章帮助我做出了取得了一些进展,但我正在尝试从电子表格中提取一些数据,例如 A10:M10,因此从一行中选择几个单元格,然后我必须将它们放入预先存在的 .csv 中,该 .csv 中已经填充了很多不会更改的字段从使用到使用,但我需要将数据从 A10:M10 获取到相当于 Z2:Z12 的 csv,这样一行到一列。这可能吗?到目前为止,我只设法让我的代码用一些标题填充空白 .csv,但我真的不认为我可以在每个字段中输入每个值。非常感谢任何帮助。
Sub WriteFile()
Dim ColNum As Integer
Dim Line As String
Dim LineValues() As Variant
Dim OutputFileNum As Integer
Dim PathName As String
Dim RowNum As Integer
Dim SheetValues() As Variant
PathName = Application.ActiveWorkbook.Path
OutputFileNum = FreeFile
Open PathName & "\file.csv" For Output Lock Write As #OutputFileNum
Print #OutputFileNum, "Field1" & "," & "Field2" & "," & "Field3" & "," & "..." & "," & "Field26"
Close OutputFileNum
End Sub
Option Explicit
Sub WriteFile()
Dim wbCSV As Workbook, ws As Worksheet
Set ws = ThisWorkbook.Sheets("Sheet1")
Set wbCSV = Workbooks.Open("existing.csv")
With wbCSV
.Sheets(1).Range("Z2:Z12") = Application.Transpose(ws.Range("A10:M10"))
.SaveAs "appended.csv"
.Close
End With
End Sub
Sub CopyRowToColumn()
' Source
Dim swb As Workbook: Set swb = ThisWorkbook ' workbook containing this code
Dim sws As Worksheet: Set sws = swb.Sheets("Sheet1")
Dim srg As Range: Set srg = sws.Range("A10:M10") ' 13 cells hence 'Z2:Z14'
' Destination
Dim dwb As Workbook
Set dwb = Workbooks.Open(swb.Path & Application.PathSeparator & "File.csv")
Dim dws As Worksheet: Set dws = wb.Sheets(1) ' the one and only
Dim dfCell As Range: Set dfCell = dws.Range("Z2")
Dim drg As Range: Set drg = dfCell.Resize(srg.Columns.Count)
' Copy values.
drg.Value = Application.Transpose(srg.Value)
' Close.
dwb.Close SaveChanges:=True
' Inform.
MsgBox "Row copied to column.", vbInformation
End Sub