最近在研究 Excel 中的 VBA ,也就是Excel 的宏,需要將第一個頁面的值,等列排入第二個Sheet頁中
就像第一個頁面中
排列成
這個樣子
首先需要縷縷自己的思路
我們需要獲取到第一個Sheet 也的值
Set Destination = Worksheets("Sheet1")
獲取到以后,要如何去找到每一列的值並賦值給另外一個Sheet 呢?
當然是,循環 + 寫入了
Dim a As Integer Dim b As Integer Dim js As Integer Set Destination = Worksheets("Sheet1") Set Destination2 = Worksheets("Sheet2") '行數 a = Destination.UsedRange.Rows.Count '列數 b = Destination.UsedRange.Columns.Count '循環行 For i = 1 To a '循環列 For j = 1 To b '計算行所在位置 js = (i * 2) '不同列不同的數據處理 If (j = 2) Then Destination2.Cells(js, j + 1) = Destination.Cells(i, j) ElseIf (j = 3) Then Destination2.Cells(js - 1, j) = Destination.Cells(i, j) Else Destination2.Cells(js - 1, j) = Destination.Cells(i, j) Destination2.Cells(js, j) = Destination.Cells(i, j) Destination2.Cells(js - 1, j + 1) = Destination.Cells(i, j) Destination2.Cells(js, j + 1) = Destination.Cells(i, j) End If Next Next
這其中Dim 就是拿來定義變量
用你獲取到的Sheet 頁數據.Cells 就是來取你某一個XY對應的數據,也可以直接進行賦值
For 的語法就是 For 變量 = 初始值 To 結束值
Next
If 的語法就簡單了
IF(條件) then 你的代碼 else 沒有否則條件可以不寫 End If
然后執行以下,我們看看
是不是 so easy?
為了以防萬一,可以在最為層加入 If Not IsError
他的用法和if 大同小異,If Not IsError(你認為可能會報錯的行) Then 如果沒有報錯的話 else 報錯了的話 On Error Resume Next
那如果我們想讓單元格稍微美觀一點,加個表格怎么辦呢?
With ActiveSheet.UsedRange.Resize(x, b - 1).Borders .LineStyle = xlContinuous .Weight = xlThin End With
簡簡單單一個 with 循環搞定
最后來個友情的彈出框
result = MsgBox("轉換完成", 0, "提示")
至於彈出框還有什么樣式,https://www.yiibai.com/vba/vba_message_box.html 闊以看看這里喲
當然里面以及空行刪除啊,或者自行填充啊,這個就是你的邏輯代碼需要處理的事情了
理論上知識點,差不多就這些吧
共同學習