Excel批量填寫表單,一段全自動的VBA代碼送給你,需要的收藏

先來看看要解決的問題


如圖1,在一張Excel工作表中,保存了許多訂單信息。

Excel批量填寫表單,一段全自動的VBA代碼送給你,需要的收藏

圖1 訂單信息數據明細

同時還有一張保存發貨單模板的工作表,如圖2。

Excel批量填寫表單,一段全自動的VBA代碼送給你,需要的收藏

圖2 發貨單模板

現需要將圖1工作表中每條訂單信息填到圖2發貨單模板中,保將結果保存為不同的工作簿,文件以訂單編號信息命名,如圖3。

Excel批量填寫表單,一段全自動的VBA代碼送給你,需要的收藏

圖3 希望得到的發貨單工作簿

看看用VBA怎麼解決這個問題

步驟一:按打開VBE窗口

步驟二:在新打開窗口左側的【工程】窗口空白處單擊鼠標右鍵,執行【插入】 →【模塊】命令,如圖4。

Excel批量填寫表單,一段全自動的VBA代碼送給你,需要的收藏

圖4 插入模塊

步驟三:雙擊插入的模塊,在右側【代碼窗口】中輸入下面的代碼,如圖5.

<code>Sub 填寫信息()
Dim Irow As Long, sht As Worksheet, t As Worksheet, Rng As Range, ToFolder As String, i As Long, Inow
Set sht = Worksheets("數據明細")
Irow = sht.Range("A1").CurrentRegion.Rows.Count

Set t = Worksheets("發貨單")
ToFolder = ThisWorkbook.Path & "\"
Application.ScreenUpdating = False
Application.DisplayAlerts = False
Set Rng = Union(t.[B3], t.[D3], t.[F3], t.[B5:B6], t.[D5:D6], t.[F5:F6], t.[B8], t.[D8], t.[F8])
For i = 2 To Irow
Rng.Value = ""
t.[B3].Value = sht.Cells(i, "A").Value
t.[D3].Value = sht.Cells(i, "B").Value
t.[F3].Value = "'" & sht.Cells(i, "C").Value
t.[B5].Value = "'" & sht.Cells(i, "D").Value
t.[B6].Value = "'" & sht.Cells(i, "G").Value
t.[D5].Value = sht.Cells(i, "E").Value
t.[D6].Value = sht.Cells(i, "H").Value
t.[F5].Value = "'" & sht.Cells(i, "F").Value
t.[F6].Value = sht.Cells(i, "I").Value
t.[B8].Value = sht.Cells(i, "J").Value
t.[D8].Value = "'" & sht.Cells(i, "K").Value
t.[F8].Value = sht.Cells(i, "L").Value
t.Cells.EntireColumn.AutoFit
t.Copy
ActiveSheet.Name = sht.Cells(i, "D").Value
ActiveWorkbook.SaveAs ToFolder & sht.Cells(i, "D").Value & ".xlsx"
ActiveWorkbook.Close
Next
Rng.Value = ""
Application.DisplayAlerts = False
Application.ScreenUpdating = True
MsgBox "操作完成,單擊【確定】按鈕查看結果。", vbInformation
Shell "explorer.exe " & ToFolder, vbNormalFocus
End Sub/<code>
Excel批量填寫表單,一段全自動的VBA代碼送給你,需要的收藏

圖5 寫入的VBA代碼

步驟四:單擊工具欄中的執行過程按鈕,執行代碼,就可以在文件夾中查看填寫所得的工作簿文件了。

Excel批量填寫表單,一段全自動的VBA代碼送給你,需要的收藏

圖6 執行寫入的代碼

具體操作過程見視頻演示:https://www.ixigua.com/i6798507687106576904/

我是葉楓,關注我,帶你學更多的Excel技巧。


分享到:


相關文章: