![](/img/trans.png)
[英]VBA: Looping through worksheets in a workbook to copy values from certain cells
[英]Iterate through row, copy value from certain cells to another Workbook
我是 VBA 中的總菜鳥,並一直在嘗試創建一個腳本,該腳本從數據庫中的以下單元格復制值(例如,從單元格 A x復制到另一個文檔中的 C11,然后從 B x復制到 C12 等),然后保存具有自定義文件名的填充文檔。
在閱讀了我想出的教程/其他堆棧流之后:
Function WypelnianieSMT()
Dim rng As Range
Dim row As Range
Set rng = Range("A2:J29")
For i = 2 To rng.Rows.Count
Workbooks("LISTA CZESCI-1.xlsm").Worksheets("Arkusz1").rng.Cells(RowIndex:=i, ColumnIndex:="H").Copy
Workbooks("Szablon Specyfikacji Materiału Technicznego.xlsx").Worksheets("Formularz klasyfikacji").Range("C11").PasteSpecial Paste:=xlPasteValues
Workbooks("LISTA CZESCI-1.xlsm").Worksheets("Arkusz1").rng.Cells(RowIndex:=i, ColumnIndex:="I").Copy
Workbooks("Szablon Specyfikacji Materiału Technicznego.xlsx").Worksheets("Formularz klasyfikacji").Range("C12").PasteSpecial Paste:=xlPasteValues
Workbooks("LISTA CZESCI-1.xlsm").Worksheets("Arkusz1").rng.Cells(RowIndex:=i + 1, ColumnIndex:="G").Copy
Workbooks("Szablon Specyfikacji Materiału Technicznego.xlsx").Worksheets("Formularz klasyfikacji").Range("C13").PasteSpecial Paste:=xlPasteValues
Workbooks("Szablon Specyfikacji Materiału Technicznego.xlsx").SaveAs Filename:="C:\***\Desktop\Makro" & Range("C2").Value & ".xlsx", FileFormat:=xlOpenXMLStrictWorkbook, CreateBackup:=False
Next
End Function
對不起伙計們,我想腳本完全一團糟,但無法解決其他問題。
使用錯誤的代碼來解釋你想要什么從來都不是一個好主意。 因此,嘗試完全接受它可能不是我的好主意。 但你做到了。 我做到了。 這就是我們現在所處的位置。 我希望它對你有用。
Function WypelnianieSMT()
' 009
' note that 'Row' is a VBA object.
' The name shouldn't be used for a user-declared variable
Dim WsList As Worksheet
Dim WsSpecs As Worksheet
Dim Fn As String ' file name
Dim C As Long ' output column
Dim R As Long ' input row
' both these workbooks must be open
Set WsList = Workbooks("LISTA CZESCI-1.xlsm").Worksheets("Arkusz1")
Set WsSpecs = Workbooks("Szablon Specyfikacji Materialu Technicznego.xlsx").Worksheets("Formularz klasyfikacji")
' Dim Rng As Range
' ' this is the joker in the deck: on which sheet is this range?
' ' it's the ActiveSheet by default. But which is the ActiveSheet?
' Set Rng = Range("A2:J29")
C = 3 ' first column to use for output
For R = 2 To 29
With WsList
.Cells(R, "H").Copy Destination:=WsSpecs.Cells(11, C)
.Cells(R, "I").Copy Destination:=WsSpecs.Cells(12, C)
.Cells(R, "G").Copy Destination:=WsSpecs.Cells(13, C)
End With
C = C + 1
Next R
' you probably don't want to save the document on every loop
' therefore delay the sdaving until the looping is done
' Range("C2") is on the WsSpecs tab???
Fn = "\Desktop\Makro" & WsSpecs.Range("C2").Value & ".xlsx"
WsSpecs.SaveAs Filename:=Environ("Userprofile") & Fn, _
FileFormat:=xlOpenXMLStrictWorkbook, _
CreateBackup:=False
End Function
該代碼完全未經測試,因為我沒有數據。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.