vba 获取范围的列索引

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11881764/
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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-08 13:44:05  来源:igfitidea点击:

get the column index of a range

vbaexcel-vbaexcel

提问by ?yvind

In the following subcode, I want to restrict what it does (replacing substring in hyperlinks) to a specific column. I have writen in '* what my idea is for a quick fix. But I can't seem to find a good way to get the column value of a cell saved as a Range variable.

在下面的子代码中,我想将它的作用(替换超链接中的子字符串)限制为特定列。我已经在 '* 中写了我的想法是为了快速修复。但我似乎无法找到一种将单元格的列值另存为 Range 变量的好方法。

Dim MyDoc As Worksheet
Dim MyCell As Range
    ...
        For Each MyCell In MyDoc.UsedRange
            If MyCell.Hyperlinks.Count > 0 Then
               '* if mycell's columnnumber = 1 then
                    LinkURL = MyCell(1).Hyperlinks(1).Address
                    FindPos = InStr(1, LinkURL, FindString)
                    If FindPos > 0 Then 'If FindString is found
                        ReplaceLen = Len(FindString)
                        URLLen = Len(LinkURL)
                        PreStr = Mid(LinkURL, 1, FindPos - 1)
                        PostStr = Mid(LinkURL, FindPos + ReplaceLen, URLLen)
                        NewURL = PreStr & ReplaceString & PostStr
                        MyCell(1).Hyperlinks(1).Address = NewURL 'Change the URL
                    End If
               '* End if
            End If
         Next MyCell

回答by assylias

You can simply call the Columnproperty:

您可以简单地调用该Column属性:

If MyCell.Column = 1 Then ...

This is the absolute column (column A of the spreadsheet), not the first column of the range.

这是绝对列(电子表格的 A 列),而不是范围的第一列。

If you want to check if it is the first column of the range, you can first calculate it:

如果要检查它是否是范围的第一列,可以先计算它:

firstCol = yourRange.Cells(1, 1).Column
If MyCell.Column = firstCol Then ...