如何在 VBA 中查找并返回列索引?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/44930216/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to find and return a column index in VBA?
提问by simpleMan
I am creating a VBA code to clear some data from multiple excel files. The problem is that the positions of the headers are not fixed and the columns slip away when I put together the files. I have to find the column index based on header name and assign them to variables.
我正在创建一个 VBA 代码来清除多个 excel 文件中的一些数据。问题是标题的位置不固定,当我把文件放在一起时,列会滑落。我必须根据标题名称找到列索引并将它们分配给变量。
I declared the range of the header to a variable. How can I return the column index to a variable?I have never done this before that is why I am asking you guys. At my first attempt I was thinking something like this:
我将标头的范围声明为一个变量。 如何将列索引返回到变量?我以前从未这样做过,这就是我问你们的原因。在我第一次尝试时,我在想这样的事情:
Set findrng = sourceWS.Range(Cells(1, 1), Cells(1, 100))
index1 = findrng.Find("COUNTRY")
index1 should store an integer like 1 or 21 ...
index1 应该存储一个整数,如 1 或 21 ...
Any help would be appreciated.
任何帮助,将不胜感激。
回答by emilyn
I am confused to what you are asking.
我对你问的感到困惑。
Is your problem that you would like to be able to search your first row for headers, and retrieve a specific column based on the header?
您是否希望能够在第一行中搜索标题并根据标题检索特定列?
thisRow = 1
searchCol = Sheet1.Cells(thisRow, 1).EntireRow.Find(What:="someString", LookIn:=xlValues, LookAt:=xlPart, SearchOrder:=xlByColumns, SearchDirection:=xlNext, MatchCase:=False).Column
? Then you can access that column with the .column
accessor.
? 然后您可以使用访问器访问该列.column
。
回答by simpleMan
Ah sorry guys I just found it. It was simple as hell...
啊抱歉伙计们,我刚找到它。简直太简单了……
ind1 = findrng.Find("COUNTRY").Column