盡管我已經在 Access 中使用它大約 6 個月了,但我還是 excel 中的 VBA 新手。我知道我的語法是導致此錯誤訊息的原因,我只是不知道我的公式哪里出錯了。我正在嘗試從同一張表中的其他 2 個欄位連接一列值得欄位(目前約為 900 個)。
我正在嘗試創建一個宏來將公式輸入到 C 列中,但老實說插入字串是我的失敗,我只是不能保持所有的引號都是直的。以下是我到目前為止撰寫的代碼 - 請告訴我我搞砸了多少!
Sub Concatenate()
Dim i As Long
Dim LastRow As Long
Dim Con As String
Dim WS As Worksheet
Set WS = Sheets("Vlookups")
'Set upper range of Loop
LastRow = Range("C" & Rows.Count).End(xlUp).Row
Application.ScreenUpdating = False
'Set to Active Worksheet
Worksheets("Vlookups").Activate
'Explicitly reference the Sheet when calling for any Range or Cell
With WS
For i = 2 To LastRow
Con = "=CONCATENATE(" & .Cells(i, 15).Select & "," & "-" & "," & .Cells(i, 16).Select & ")"
.Cells(i, 3).Select
ActiveCell.Formula = Con
Next i
End With
Application.ScreenUpdating = False
End Sub
==================================================== ============== 為將來搜索的任何人留下原始問題和代碼。下面是最終解決我的問題的代碼,由@BigBen提供。
Sub Concatenate()
Dim LastRow As Long
'Set upper range of Loop
LastRow = Range("O" & Rows.Count).End(xlUp).Row
'Reduce time taken to run Macro
Application.ScreenUpdating = False
WS.Range("C2:C" & LastRow).Formula = "=O2&""-""&P2"
Application.ScreenUpdating = True
End Sub
uj5u.com熱心網友回復:
- 沒有必要
Select或Activate。 - 無需回圈。
- 看起來您正在根據 C 列找到最后一行,但隨后將公式寫入 C 列,這似乎很可疑。也許根據 O 列或 P 列找到最后一行?
- 沒有必要使用
CONCATENATE公式。
With WS
' find last row based on column O, or maybe P
LastRow = .Range("O" & .Rows.Count).End(xlUp).Row
.Range("C2:C" & LastRow).Formula = "=O2&""-""&P2"
End With
如果您實際上想要在公式中使用硬編碼字串而不是單元格參考,那么:
With WS
' find last row based on column O, or maybe P
LastRow = .Range("O" & .Rows.Count).End(xlUp).Row
For i = 2 to LastRow
Range("C" & i).Formula = "=""" & Range("O" & i).Value & "-" & Range("P" & i).Value & """"
Next
End With
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/529608.html
下一篇:洗掉公式中的括號
