我在创建 vba 代码以将两个单元格连接成一个单元格时遇到问题。这两个单元格由数字和文本组成。
我已经创建了从另一个工作簿导入数据的代码,并使 vba 使用 offset(1,0) 将数据粘贴到可用的下一行。但是,我不知道如何使 vba 将 A 列和 B 列中的每个单元格连接到 C 列中的单元格。
我希望用下划线将其连接起来:单元格 A_单元格 B
提前谢谢您
'Import Data
Dim FileToOpen As Variant
Dim openbook As Workbook
Application.ScreenUpdating = False
FileToOpen = Application.GetOpenFilename(Title:="Browse for your File & Import Range", Filefilter:="Excel Files (*.xlsx),*.xlsx")
If FileToOpen <> False Then
Set openbook = Application.Workbooks.Open(FileToOpen)
openbook.Sheets(1).Range("A1").CurrentRegion.Copy
ThisWorkbook.Worksheets("NO PK").Range("A" & Rows.Count).End(xlUp).Offset(1, 0).PasteSpecial xlPasteValues
openbook.Close False
End If
Application.ScreenUpdating = True
为单元格赋值比粘贴值更有效。
应用公式连接 Col A 和 B,然后将公式转换为值。
微软文档:
Dim FileToOpen As Variant
Dim openbook As Workbook
Application.ScreenUpdating = False
FileToOpen = Application.GetOpenFilename(Title:="Browse for your File & Import Range", Filefilter:="Excel Files (*.xlsx),*.xlsx")
If FileToOpen <> False Then
Set openbook = Application.Workbooks.Open(FileToOpen)
Dim srcRng As Range, RowCnt As Long, ColCnt As Long
Set srcRng = openbook.Sheets(1).Range("A1").CurrentRegion
RowCnt = srcRng.Rows.Count
ColCnt = srcRng.Columns.Count
With ThisWorkbook.Worksheets("NO PK").Range("A" & Rows.Count).End(xlUp).Offset(1, 0).Resize(RowCnt, ColCnt)
.Value = srcRng.Value
With .Columns(3) ' Col C
' Apply formula to concate Col A, Col B
.FormulaR1C1 = "=RC[-2] & ""-"" & RC[-1]"
' Convert formulas to values
.Formula = .Value
End With
End With
.PasteSpecial xlPasteValues
openbook.Close False
End If
Application.ScreenUpdating = True