gpt4 book ai didi

VBA宏: Formula is Based on a Column that changes locations

转载 作者:行者123 更新时间:2023-12-02 11:58:32 25 4
gpt4 key购买 nike

我正在尝试调整我的宏,以便它在始终更改位置的特定列旁边创建一个列。在我下面的宏中,它只是左侧 6 列的绝对引用。然而,情况并非总是如此。我应该通过查找顶行中的列名称来设置它吗?

基本上,宏创建一个新列,如果重复,则放入 IF 语句,然后设置条件格式以突出显示所有“1”值。抱歉,如果我没有解释清楚!

Sub test()
Columns("L:L").Select
Selection.Insert Shift:=xlToRight
Range("L2").Select
ActiveCell.FormulaR1C1 = "=IF(RC[-6]=R[-1]C[-6],R[-1]C+1,1)"
Range("L2").Select
Selection.Copy
Range("K2").Select
Selection.End(xlDown).Select
ActiveCell.Offset(0, 1).Select
Range(Selection, Selection.End(xlUp)).Select
ActiveSheet.Paste
Application.CutCopyMode = False
Calculate
Selection.FormatConditions.Add Type:=xlCellValue, Operator:=xlEqual, _
Formula1:="=1"
Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
With Selection.FormatConditions(1).Font
.Color = -16383844
.TintAndShade = 0
End With
With Selection.FormatConditions(1).Interior
.PatternColorIndex = xlAutomatic
.Color = 13551615
.TintAndShade = 0
End With
Selection.FormatConditions(1).StopIfTrue = False
End Sub

最佳答案

我有一个可用的代码,但它要求您的数据位于表中。这是动态操作和引用数据(列、行等)的最佳方式

我也严重依赖 ListObject 方法。它确实可以很好地处理表格。

Public Sub InsertColumn(Optional columnName As String, Optional BeforeORAfter As String)
Dim loTableName As ListObject
Dim loColumn As ListColumn
Dim newColDest As Long

'Handles user input if they desire the column inserted before or after
Select Case UCase(BeforeORAfter)
Case Is = "BEFORE"
newColDest = 0 'Inserts column and moves reference column right
Case Else
newColDest = 1 'Inserts column to the right of reference column
End Select

'Ensures the user selects a reference column name
Select Case columnName
Case Is = ""
columnName = InputBox("Enter column name to be referenced.", "Enter Column Name")
Case Else
End Select

'Sets the ListObject as the table.
Set loTableName = Range("TableName").ListObject

With loTableName
On Error GoTo InsertError 'Exits sub in case the column couldn't be found
.ListColumns.Add (.ListColumns(columnName).Index + newColDest)
End With
Exit Sub

InsertError:
'Most likely error is user typed the column header incorrectly.
MsgBox "Error creating column. Ensure a correct reference column was chosen", vbExclamation + vbOKOnly, "Insert Error"

End Sub

如有任何疑问或问题,请告诉我。

关于VBA宏: Formula is Based on a Column that changes locations,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22103539/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com