gpt4 book ai didi

excel - 在 Excel VBA 中设置全局变量

转载 作者:行者123 更新时间:2023-12-04 21:18:42 25 4
gpt4 key购买 nike

我正在处理一个带有多个选项卡的 Excel 项目。
其中一个工作表有一个名为“名称”的列。我的用户通常不时地移动列。因此,为了提取正确的列,我使用了这个特定的 VBA 代码。

HEADER = Sheets("WORKSHEET").Range("A1:Z1").Address
SourceDataColumn = Application.WorksheetFunction.Match("Name", HEADER, 0)
SourceColumnLetter = Split(Cells(1, SourceDataColumn).Address(True, False), "$")(0)
示例:在这种情况下,输出将是 [ SourceColumnLetter = C ],其中包含“名称”
它工作正常,我只是想知道是否有办法将“SourceColumnLetter”设置为全局变量,这样我就不必一次又一次地使用相同的整个代码块。
任何帮助,将不胜感激。
提前致谢。

最佳答案

制作函数GetColumnNumberByTitle为您找到列号。然后,您可以通过其编号轻松访问它。
您可以使用 GetColumnNumberByTitle("Name")现在在您的任何程序中按标题获取列。请注意,它返回 0如果没有找到 "Name" .
请参见下面的示例:

Option Explicit

Public Sub test()
Dim ColNo As Long
ColNo = GetColumnNumberByTitle("Name") 'get the column number by its title in row 1

If ColNo <> 0 Then
'access the column by its number
Debug.Print ThisWorkbook.Worksheets("WORKSHEET").Cells(1, ColNo)
'this should return the column name

Debug.Print ThisWorkbook.Worksheets("WORKSHEET").Cells(2, ColNo)
'this should return the columns first value
Else
MsgBox "Column Name was not found."
End If
End Sub

Public Function GetColumnNumberByTitle(ByVal ColumnTitle As String) As Long
On Error Resume Next 'next line errors if title is not found
GetColumnNumberByTitle = Application.WorksheetFunction.Match(ColumnTitle, ThisWorkbook.Worksheets("WORKSHEET").Rows(1), 0)
On Error GoTo 0 're-enable error reporting!
'if title was not found this function returns 0
End Function
另一种方法可能是使用格式化表(ListObjects):
enter image description here
然后,您可以使用以下代码通过标题轻松访问列:
Worksheets("Sheet1").ListObjects("Table1").ListColumns("Name").Range.Select
或选择特定行
Worksheets("Sheet1").ListObjects("Table1").ListColumns("Name").Range(3).Select
'selects row 3 in column "Name"

关于excel - 在 Excel VBA 中设置全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63828883/

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