我有一个 excel vba 工作流程,可以将数据从数据输入表(inputwks)输入到表格中。这将如下所示:
我不想使用列字母或数字,因为我可能会更改顺序(例如,日期/时间在 A 列而不是 M 列中的用户可能看起来更好)。
如何更改下面的代码,以便宏将搜索“日期/时间”列而不是转到 M 列,“数据记录”也是如此?
感谢您提供的任何帮助。
Sub UpdateLogWorksheet()
'Dim historyWks As Worksheet
Dim ccarWks As Worksheet
Dim inputWks As Worksheet
Dim nextRow As Long
Dim oCol As Long
'======================Named range setup=========================
Dim myCopy As Range
Dim myTest As Range
Dim lRsp As Long
'=====================worksheet name setup=======================
Set inputWks = Worksheets("Input (Modded)")
Set ccarWks = Worksheets("CCAR - VB Template Ver2.0")
oCol = 3
'===================Copy/paste data commands==================
Set myCopy = inputWks.Range("inputvalue")
With ccarWks
nextRow = .Cells(.Rows.Count, "A").End(xlUp).Offset(1, 0).Row
End With
With ccarWks
With .Cells(nextRow, "M") 'was "A"
.Value = Now
.NumberFormat = "dd/mm/yyyy hh:mm:ss" 'enter date and time stamp in record
End With
myCopy.Copy
.Cells(nextRow, 3).PasteSpecial Paste:=xlPasteValues, Transpose:=True
Application.CutCopyMode = False
End With
End Sub
最佳答案
我过去也不得不处理这个问题,因为源表已经改变,你不能确定字段是否在同一列中。
如果您总是有相同的字段标题(列标题),那么您可以使用我之前使用过的代码。
Public Function FindColumn(ws As Worksheet, name As String, Optional headerRow As Integer = 1) As Integer
On Error GoTo FUNC_ERR
Dim sRng As Range: Set sRng = ws.Rows(headerRow).Find(what:=name, _
LookIn:=xlValues, _
lookat:=xlWhole)
If sRng Is Nothing Then
'Handle if not found
Else
FindColumn = sRng.Column
End If
FUNC_EXIT:
Exit Function
FUNC_ERR:
'Handle error
End Function
HeaderRow 是可选的,假定为第 1 行,但如果需要,您也可以调用不同的行。
然后不要使用
.cell()
中的列字母标注,您可以使用返回的列号。dim columnNumber as Integer: columnNumber = FindColumn(ccarWks, "Header Name")
With ccarWks
With .Cells(nextRow, columnNumber)
.Value = Now
.NumberFormat = "dd/mm/yyyy hh:mm:ss"
End With
'...more code...
End With
希望这对您有所帮助。
关于excel - 根据表格标题自动在单元格中输入日期/时间戳的代码,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56672357/